Array Helper Methods in ES6
Array helper methods in ES6 (JavaScript) are extremely useful for working with data stored in arrays. As a web developer, you often work with arrays, whether they contain simple numbers or complex objects with many attributes. These methods significantly simplify the manipulation of arrays, making it easier to perform complex tasks and handle intricate arrays of objects.
There are several array methods available in JavaScript ES6 which are as follows:
Table of Content
- Using forEach() method
- Using map() method
- Using filter() method
- Using find() method
Using forEach() method
The forEach() method is used to iterate over all the entries of the array.
Example: To demonstrate finding the sum of all the numbers in an array of numbers.
let sum = 0;
const numbers = [1, 2, 3, 4, 5];
numbers.forEach((num) => {
sum = sum + num;
});
console.log(sum);
Output
15
Using map() method
The map() method is used to iterate through all the entries of the array, modifies them and returns a new array but the old array is not manipulated.
Example: To demonstrate multiplying each number of the array by 2 and generating a new array.
const numbers = [1, 2, 3, 4, 5];
let double = numbers.map((num) => {
// Its mandatory to have a
// return while using map
return num * 2;
});
console.log(double);
Output
[ 2, 4, 6, 8, 10 ]
Example: The map() method can also be used to extract attributes from an array of objects and store it in another array.
const objects = [
{ a: 1, b: 2 },
{ a: 3, b: 4 },
{ a: 5, b: 6 }
];
let onlybs = objects.map((object) => {
return object.b;
});
console.log(onlybs);
Output
[ 2, 4, 6 ]
Using filter() method
The filter() method is used to iterate through all the entries of the array and filters out required entities into another array.
Example: To demonstrate filtering all objects where flag is 1.
let objects = [
{ flag: 1, a: 1 },
{ flag: 0, a: 2 },
{ flag: 1, a: 3 }
];
objects.filter((object) => {
if (object.flag === 1) {
// Display the result
console.log("flag:" + object.flag
+ ", a:" + object.a);
}
});
Output
flag:1, a:1 flag:1, a:3
Using find() method
The find() method is used to iterate through all the entries of the array and returns the record matching with a particular condition.
Example: To demonstrate finding an object where flag is 0.
let objects = [
{ flag: 1, a: 1 },
{ flag: 0, a: 2 },
{ flag: 1, a: 3 }
];
// Use find() function to
// filter the object
objects.find((object) => {
if (object.flag === 0) {
// Display the result
console.log("flag:" + object.flag
+ ", a:" + object.a);
}
});
Output
flag:0, a:2