Array Helper Methods in ES6 (JavaScript) are very useful for working with data stored in arrays. Most of the time working as a web developer work with data stored in arrays it may be a simple array of numbers or it may be a complex array of objects where each object is containing a lot of attributes. Array Helper Methods helps lot in working with arrays. Array Helper Methods can be used for complex tasks with array very easily and can also easily work with complex arrays of objects.
forEach(): The forEach() function is used to iterates through all the entries of the array.
Example: To find the sum of all the numbers in an array of numbers.
<script> let sum = 0; const numbers = [1, 2, 3, 4, 5]; numbers.forEach( (num) => { sum = sum + num; }); document.write(sum); // 15 </script> |
Output:
15
map(): 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 multiply each number of the array by 2 and generate a new array.
<script> const numbers = [1, 2, 3, 4, 5]; let double = numbers.map( (num) => { // Its mandatory to have a // return while using map return num * 2; }); document.write(double); // [2, 4, 6, 8, 10] </script> |
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.
<script> const objects = [ {a:1, b:2}, {a:3, b:4}, {a:5, b:6} ]; let onlybs = objects.map( (object) => { return object.b; }); document.write(onlybs); // [2, 4, 6] </script> |
Output:
2, 4, 6
filter(): The filter() method is used to iterate through all the entries of the array and filters out required entities into another array.
Example: To filter all objects where flag is 1.
<script> let objects = [ {flag:1, a:1}, {flag:0, a:2}, {flag:1, a:3} ]; // Use filter() function to // filter the object objects.filter((object) => { if (object.flag === 1) { // Display the result console.log( "flag:" + object.flag + ", a:" + object.a); } }); </script> |
Output:
flag:1, a:1 flag:1, a:3
find(): 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 find a object where flag is 0.
<script> 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); } }); </script> |
Output:
flag:0, a:2
Note: The filter() method returns an array of objects and find() method returns a single object.