JavaScript Map, Filter And Reduce


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.
  1. var numbers = [1, 2, 3, 4, 2, 1];  
  2. var newNumbers = [];  
  3. for(var i = 0; i < numbers.length; i++) {  
  4.     if(numbers.indexOf(numbers[i]) === i) {  
  5.         newNumbers.push(numbers[i]);  
  6.     }  
  7. }  
  8. console.log("The Non duplicate numbers are", newNumbers);  
  9. //Output: [3, 4] 
So as in the above implementation, there are five steps involved in this task:
Code Line Meaning
var i = 0 initialization
i < numbers.length condition 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. 
  1. var newNumbers = numbers.filter(function(ele, index, numbers) {  
  2.     return(numbers.indexOf(elem) === index);  
  3. }); 
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 implementation JavaScript functional approach
Code line #1,#2,#3 is required filter() calculate automatically
Code line #4 make use of if the condition filter() does not require any if block
Code line #5 where newNumbers must be a list or an array, their data type is checked filter() does not require to check all these constraints
Now let us discuss the concepts and implementations of these methods in detail.


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.
  1., index, array) {  
  2.     //do something     
  3. }, thisValue); 
Arguments Descriptions
ele The value of the current element. (Required)
index The array index of the current element.(Optional)
array Actual array object invoking the method. (Optional)
thisValue If '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.
  1. var numbers = [1, 2, 3, 4, 5];  
  2. var square = {  
  3.     return(elem * elem);  
  4. });  
  5. //output: square=[1,4,9,16,25] 
Example 2- Mapping with the array of objects for specific key value. 
  1. var players=[{firstname:"Sachin",lastname:"Tendulakar",Age:42},{firstname:"Virat",lastname:"Kohli",Age:27},{firstname:"Yuvraj",lastname:"Singh",Age:34}],{return a.firstname}); 


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.
  1. array.filter(function(ele, index, array) {  
  2.     //do something     
  3. }, 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.
  1. var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];  
  2. var evenNum = numbers.filter(function(ele) {  
  3.     return((ele % 2) == 0);  
  4. });  
  5. //output: evenNum=[2,4,6,8,10] 
Example 2- Filtering the array of objects on the basis of specific key value. 
  1. var players = [{  
  2.     firstname: "Sachin",  
  3.     lastname: "Tendulkar",  
  4.     type: "batsman"  
  5. }, {  
  6.     firstname: "Ashish",  
  7.     lastname: "Nehra",  
  8.     type: "bowler"  
  9. }, {  
  10.     firstname: "Yuvraj",  
  11.     lastname: "Singh",  
  12.     type: "batsman"  
  13. }, {  
  14.     firstname: "Ravichandran",  
  15.     lastname: "Ashwin",  
  16.     type: "bowler"  
  17. }];  
  18. var batsman = players.filter(function(ele) {  
  19.             return(ele.type === 'batsman});     
  20.                     //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. 
  1. var batsman = players.filter(function(ele) {  
  2.             return(ele.type === 'batsman}).map(function(ele) {     
  3.                 return(ele.firstname + " " + ele.lastname);  
  4.             });  
  5.         //output: batsman=[Sachin Tendulkar,Yuvraj Singh] 


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.
  1. array.reduce(function(prevValue, curValue, index, array) {  
  2.     //do something     
  3. }, initialValue); 
Arguments Description
prevValue The value which is previously returned in the last invocation of the callback function. (Required)
curValue The current value being processed in the array. (Required)
index The array index of the current element value.(Optional)
array Actual array object invoking the method. (Optional)
initialValue A 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.
  1. var numbers = [1, 2, 3, 4, 5];  
  2. var sum = numbers.reduce(function(preValue, curValue) {  
  3.     return(preValue + curValue);  
  4. });  
  5. //output: sum=15 
Example 2- Reduce the given array of objects corresponding to the specific key value. 
  1. var empDetails = [{  
  2.     empName: "Dinesh",  
  3.     branch: "Developer",  
  4.     salary: 60000  
  5. }, {  
  6.     empName: "Ashish",  
  7.     branch: "Tester",  
  8.     salary: 45000  
  9. }, {  
  10.     empName: "Mitesh",  
  11.     branch: "Mobile",  
  12.     salary: 35000  
  13. }, {  
  14.     empName: "Avinash",  
  15.     branch: "Designer",  
  16.     salary: 40000  
  17. }];  
  18. var salaries = {  
  19.     return(ele.salary);  
  20. });  
  21. var totalSalary = salaries.reduce(function(prev, curr) {  
  22.     return(prev + curr);  
  23. });  
  24. // Or you can simplify the above code as shown below:     
  25. var totalSalary = {  
  26.     return(ele.salary);  
  27. }).reduce(function(prev, curr) {  
  28.     return(prev + curr);  
  29. });  
  30. //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.
Read more articles on JavaScript