JavaScript map(), filter(), and reduce(): A Comprehensive Guide

Learn to use JavaScript's map(), filter(), and reduce() functions like a pro. This comprehensive guide covers everything you need to know, from the basics of these powerful functions to advanced techniques. Whether you're a beginner or a seasoned pro, you'll learn how to use map(), filter(), and reduce() to write more efficient and elegant JavaScript code. 

We are very familiar with arrays, which is popularly known as a collection of similar types of elements such as numbers, strings, objects etc. We traverse the array by iterating over the elements through their index using a loop.

In 2011, JavaScript introduced the concept of map, filter, and reduce. These are the methods that act as an alternative to the traversal by the loop. These methods help to translate the array elements, find its cumulative values, or build the subset based on conditions. The advantage of using these methods reduces the complexity of the code and makes the code more readable.

Traditional Approach

The below code snippet which is an implementation of a for loop, to traverse over the elements of an array and inserts the non-duplicate elements to a new array.

var numbers = [1, 2, 3, 4, 2, 1];  
var newNumbers = [];  
for(var i = 0; i < numbers.length; i++) {  
    if(numbers.indexOf(numbers[i]) === i) {  
        newNumbers.push(numbers[i]);  
    }  
}  
console.log("The Non duplicate numbers are", newNumbers);  
//Output: [3, 4] 

So as in the above implementation, there are five steps involved in this task:

Code LineMeaning
var i = 0initialization
i < numbers.lengthcondition to iterate till the last element
i++increments by one
if(numbers.indexOf(numbers[i])=== i))condition to check duplicate entries
newNumbers.push(numbers[i])newNumbers is an array which stores the non-duplicate entries

The above implementation can be done by making use of filter() function of javascript. 

var newNumbers = numbers.filter(function(ele, index, numbers) {  
    return(numbers.indexOf(elem) === index);  
});

So the above implementation may confuse those readers who are new to this concept. But one thing you can notice the difference in lines of code as compared to for loop implementation. 

for loop implementationJavaScript functional approach
Code line #1,#2,#3 is requiredfilter() calculate automatically
Code line #4 make use of if the conditionfilter() does not require any if block
Code line #5 where newNumbers must be a list or an array, their data type is checkedfilter() does not require to check all these constraints

Now let us discuss the concepts and implementations of these methods in detail.

map()

When you want to translate or map all the elements of an array to another array. The map() method calls the provided callback function once for each element in an array, in order. It doesn’t change the original array.

Syntax

array.map(function(ele, index, array) {  
    //do something     
}, thisValue);
ArgumentsDescriptions
eleThe value of the current element. (Required)
indexThe array index of the current element.(Optional)
arrayActual array object invoking the method. (Optional)
thisValueIf 'thisValue' parameter is provided, it will be used as ‘this’ for each invocation of a callback function.Ifthis parameter is empty then the value ‘undefined’ will be passed as its ‘this’ value. (Optional)

The following sample, examples showing map() method implementation:Example 1- Convert the given array elements to its square value.

var numbers = [1, 2, 3, 4, 5];  
var square = numbers.map(function(ele) {  
    return(elem * elem);  
});  
//output: square=[1,4,9,16,25] 

Example 2- Mapping with the array of objects for specific key value. 

var players=[{firstname:"Sachin",lastname:"Tendulakar",Age:42},{firstname:"Virat",lastname:"Kohli",Age:27},{firstname:"Yuvraj",lastname:"Singh",Age:34}],firstNames=players.map(function(a){return a.firstname}); 

filter()

When you want to translate or map the elements of an array to another array based on certain conditions. The filter() method calls the provided callback function once for each element in an array, checks for the provided test condition, and only return those elements which satisfy the given test condition. It doesn’t change the original array.

Syntax

array.filter(function(ele, index, array) {  
    //do something     
}, thisValue);

The description of the arguments is the same as that of a map() method.

The following sample, examples showing filter() method implementation:Example 1- Filtering out the odd numbers of the given array.

var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];  
var evenNum = numbers.filter(function(ele) {  
    return((ele % 2) == 0);  
});  
//output: evenNum=[2,4,6,8,10] 

Example 2- Filtering the array of objects on the basis of specific key value. 

var players = [{  
    firstname: "Sachin",  
    lastname: "Tendulkar",  
    type: "batsman"  
}, {  
    firstname: "Ashish",  
    lastname: "Nehra",  
    type: "bowler"  
}, {  
    firstname: "Yuvraj",  
    lastname: "Singh",  
    type: "batsman"  
}, {  
    firstname: "Ravichandran",  
    lastname: "Ashwin",  
    type: "bowler"  
}];  
var batsman = players.filter(function(ele) {  
            return(ele.type === 'batsman});     
                    //output: batsman=[object Object],[object Object] 

As shown above, the output will contain those filtered objects based on the test condition, we need to apply the map() method to obtain the specific key value of those objects. 

var batsman = players.filter(function(ele) {  
            return(ele.type === 'batsman}).map(function(ele) {     
                return(ele.firstname + " " + ele.lastname);  
            });  
        //output: batsman=[Sachin Tendulkar,Yuvraj Singh] 

reduce()

When you want to reduce the array to a single value. This method executes a provided callback function for each element of the array which has a value from left to right. The returned value of the function is stored in a variable as total.Syntax

array.reduce(function(prevValue, curValue, index, array) {  
    //do something     
}, initialValue); 
ArgumentsDescription
prevValueThe value which is previously returned in the last invocation of the callback function. (Required)
curValueThe current value being processed in the array. (Required)
indexThe array index of the current element value.(Optional)
arrayActual array object invoking the method. (Optional)
initialValueA value to be passed to the function as the first argument to the first call of the callback function. (Optional)

Example 1- Calculate the sum of numbers of the given array elements.

var numbers = [1, 2, 3, 4, 5];  
var sum = numbers.reduce(function(preValue, curValue) {  
    return(preValue + curValue);  
});  
//output: sum=15 

Example 2- Reduce the given array of objects corresponding to the specific key value. 

var empDetails = [{  
    empName: "Dinesh",  
    branch: "Developer",  
    salary: 60000  
}, {  
    empName: "Ashish",  
    branch: "Tester",  
    salary: 45000  
}, {  
    empName: "Mitesh",  
    branch: "Mobile",  
    salary: 35000  
}, {  
    empName: "Avinash",  
    branch: "Designer",  
    salary: 40000  
}];  
var salaries = empDetails.map(function(ele) {  
    return(ele.salary);  
});  
var totalSalary = salaries.reduce(function(prev, curr) {  
    return(prev + curr);  
});  
// Or you can simplify the above code as shown below:     
var totalSalary = empDetails.map(function(ele) {  
    return(ele.salary);  
}).reduce(function(prev, curr) {  
    return(prev + curr);  
});  
//output: totalSalary=180000 

In this post, I have covered the basic concepts of the array’s map, filter, and reduce methods along with their implementation with examples. In a real-time scenario like in certain web applications you might be dealing with the JSON data that will be required to be processed on certain key values, in that case, you can implement these methods to fulfill the requirement in a more convenient way rather than following the traditional approach.

#javascript

JavaScript map(), filter(), and reduce(): A Comprehensive Guide
24.40 GEEK