๐ Introduction:
Arrays are one of the most commonly used data structures in JavaScript. They are used to store and manipulate collections of data.
While coding in JavaScript, it is most likely that you will fall under circumstances where you have to manipulate an array.
JavaScript has a variety of built-in array methods that make it easier to work with arrays. In this blog post, we will explore some of the modern array methods in JavaScript and provide examples using emojis to make it fun and easy to understand.
๐ forEach():
The forEach() method executes a provided function once for each array element.
const emojis = ["๐", "๐", "๐", "๐"];
emojis.forEach((emoji) => {
console.log(emoji);
});
// Output:
// ๐
// ๐
// ๐
// ๐
๐ map():
The map() method creates a new array with the results of calling a provided function on every element in the calling array.
const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers.map((number) => {
return number * 2;
});
console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]
๐ filter():
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter((number) => {
return number % 2 === 0;
});
console.log(evenNumbers); // Output: [2, 4]
๐ find():
The find() method returns the value of the first element in the array that satisfies the provided testing function.
const emojis = ["๐", "๐", "๐", "๐"];
const happyEmoji = emojis.find((emoji) => {
return emoji === "๐" || emoji === "๐";
});
console.log(happyEmoji); // Output: "๐"
๐ reduce():
The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.
const numbers = [1, 2, 3, 4, 5];
const sumOfNumbers = numbers.reduce((accumulator, currentValue) => {
return accumulator + currentValue;
}, 0);
console.log(sumOfNumbers); // Output: 15
๐ some():
The some() method tests whether at least one element in the array passes the test implemented by the provided function.
const numbers = [1, 2, 3, 4, 5];
const hasEvenNumber = numbers.some((number) => {
return number % 2 === 0;
});
console.log(hasEvenNumber); // Output: true
๐ every():
The every() method tests whether all elements in the array pass the test implemented by the provided function.
const numbers = [2, 4, 6, 8, 10];
const allEvenNumbers = numbers.every((number) => {
return number % 2 === 0;
});
console.log(allEvenNumbers); // Output: true