Handle element in an Array
const hobbies = ["sports", "cooking", "reading"];
console.log(hobbies[0]); # Get single element
hobbies.push("surfing"); # Add new element to the end
hobbies.unshift("movies"); # Add new element to th start
hobbies.pop(); # remove the last element
hobbies.shift(); # remove the first element
Find element
const index = hobbies.findIndex((item) => {
return item === "reading"
});
console.log(index);
A shorter code:
const index = hobbies.findIndex((item) => item === "reading");
console.log(index);
// Result
2
Find an element in Object
const inventory = [
{ name: "apples", quantity: 2 },
{ name: "bananas", quantity: 0 },
{ name: "cherries", quantity: 5 },
];
const result = inventory.find(({ name,quantity }) => name === "cherries");
console.log(result);
// Result:
{ name: 'cherries', quantity: 5 }
find()
method ONLY returns the first element in the provided array that satisfies the provided testing function
Filter
const words = ['spray', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter((word) => word.length > 6);
// Result:
["exuberant", "destruction", "present"]
Iterate Array
const newHobbies = hobbies.map((item) => item + "!");
consoloe.log(newHobbies);
// Result
(3) ["sports!", "cooking!", "reading!"]
Combine Array
const numbers = [1,2,4,5];
const all = [...hobbies, ...numbers];
console.log(all);
// Result
(7) ["sports", "cooking", "reading", 1, 2, 4, 5]
Destruct an Array
const userName = ["John", "Ted"];
// Old School Way
// const firstName = userName[0];
// const lastName = userName[1];
// New Way
const [firstName, lastName] = ["John", "Ted"];
console.log(firstName);
console.log(lastName);
// Result:
John
Ted
We can also destruct an Object like this:
const {name,quantity} = { name: "apples", quantity: 2 };
console.log(name);
console.log(quantity);
// Result:
apples
2