Friday, January 6, 2023

JavaScript Arrays

 // Arrays

const certifications = ['Admin','PD1','PD2'];
console.log(certifications);

const versions = new Array('WI21','SP21','SU21');
console.log(versions);

// To add the element at last index
const length = certifications.push('CPQ'); // returns the length
console.log(certifications);
console.log(length);

// To add the element at the begining of the index 
certifications.unshift('App Builder'); // returns the length
console.log(certifications);

// To remove the last element from array
const removedCer = certifications.pop(); // returns the removed element
console.log(removedCer);
console.log(certifications);

// To remove the first element from array
const removedCer2 = certifications.shift(); // returns the removed element
console.log(removedCer2);
console.log(certifications);

// Identify index based on the value 
console.log(certifications.indexOf('PD1')); // -1 if the element is not there
// ES6 includes returns true or false (strict equality)


// Slice won't modify the existing array
const clouds = ['sales', 'service', 'marketing', 'digitalExperience', 'health'];

console.log(clouds.slice(2));
// expected output: Array ['marketing', 'digitalExperience', 'health']

console.log(clouds.slice(2, 4));
// expected output: Array ['marketing', 'digitalExperience']

console.log(clouds.slice(1, 5));
// expected output: Array ['service', 'marketing', 'digitalExperience', 'health']

console.log(clouds.slice(-2));
// expected output: Array ['digitalExperience', 'health']

console.log(clouds.slice(2, -1));
// expected output: Array ['marketing', 'digitalExperience']

// Splice modify the exiting array

//splice(start)
//splice(start, deleteCount)
//splice(start, deleteCount, item1)
//splice(start, deleteCount, item1, item2, itemN)


const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 2, 'Feb');
// inserts at index 1
console.log(months);
// expected output: Array ["Jan", "Feb", "June"]

months.splice(4, 1, 'May');
// replaces 1 element at index 4
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "May"]

No comments:

Post a Comment

Understanding Wire vs Imperative Apex Method Calls in Salesforce Lightning Web Components (LWC)

Understanding Wire vs Imperative Apex Method Calls in Salesforce Lightning Web Components (LWC) Introduction: Salesforce Lightning Web ...