Tuesday, November 19, 2024
Google search engine
HomeLanguagesJavascriptHow to use map(), filter(), and reduce() in JavaScript ?

How to use map(), filter(), and reduce() in JavaScript ?

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
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments