The map(), filter(), and reduce() are the array functions that allow us to manipulate an array according to our own logic and return a new array after applying the modified operations on it. These methods are very popular among JavaScript developers as they make the code short, simple, and clean. These array functions replace the traditional approach of iterating an array using for loop. These methods are also known as higher order functions. These methods use a callback function to implement the logic
JavaScript map() Method: This method is used to apply a particular operation on each element of the array in a callback function and then return the updated array
Syntax:
arr.map(function(args){ ... })
Example: In this example, we will use the map() method to add 2 to each array element
Javascript
var arr= [2,4,8,10] var updatedArr = arr.map(val=> val+2) console.log(arr); console.log(updatedArr); |
Output:
(4) [2, 4, 8, 10] (4) [4, 6, 10, 12]
JavaScript filter() Method: This method is used to return an array that contains the elements which satisfy the condition applied inside the callback function
Syntax:
arr.filter(function(){ // condition })
Example: In this example, we will use the filter() method to get the elements smaller than 5 in an array.
Javascript
var arr= [2,4,8,10] var updatedArr = arr.filter(val=> val<5) console.log(arr); console.log(updatedArr); |
Output:
(4) [2, 4, 8, 10] (2) [2, 4]
JavaScript reduce() Method: This method is used to apply a callback function to each element in an array and return a single element
Syntax:
arr.reduce(function(){ ... })
Example: In this example, we will use reduce() method to calculate the sum of the array.
Javascript
var arr= [2,4,8,10] var updatedArr = arr.reduce((prev, curr)=> curr= prev+curr) console.log(arr); console.log(updatedArr); |
Output
(4) [2, 4, 8, 10] 24
The table below shows the comparison of properties of the above-mentioned methods:
Property |
map() |
filter() |
reduce() |
---|---|---|---|
Return type | Returns a new array | Returns a new array | Returns a single element |
Action | Modifies each element of the array | Filter out the element which passes the condition | Reduces array to a single value |
Parameters | value, index, array | value, index, array | accumulator, value, index, array |