JavaScript Map, Filter And Reduce

We are very familiar with arrays, which is popularly known as a collection of similar type 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 which 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.   
  4. for(var i = 0; i < numbers.length; i++)   
  5. {   
  6. if(numbers.indexOf(numbers[i])===i)   
  7. {   
  8. newNumbers.push(numbers[i]);   
  9. }   
  10. }   
  11. console.log("The Non duplicate numbers are", newNumbers);   
  12. //Output: [3, 4]  

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

Code Line Meaning
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. 

  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 implementationJavaScript functional approach
Code line #1,#2,#3 is requiredfilter() calculate automatically
Code line #4 make use of if 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:

  1. array.map(function(ele,index,array){   
  2. //do something   
  3. },thisValue);  
Arguments Descriptions
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)

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=numbers.map(function(ele){   
  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 = [   
  2. {firstname : "Sachin", lastname: "Tendulakar",Age:42},   
  3. {firstname : "Virat", lastname: "Kohli",Age:27},   
  4. {firstname : "Yuvraj", lastname: "Singh",Age:34}   
  5. ];   
  6. var firstNames=players.map(function(ele){   
  7. return (ele.firstname);   
  8. });   
  9. //output: firstNames=[Sachin,Virat,Yuvraj]  

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:

  1. array.filter(function(ele,index,array){   
  2. //do something   
  3. },thisValue);  
The description of the arguments is same as that of a map() method.

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", lastname: "Tendulkar",type:"batsman"},   
  3. {firstname : "Ashish", lastname: "Nehra",type:"bowler"},   
  4. {firstname : "Yuvraj", lastname: "Singh",type:"batsman"},   
  5. {firstname : "Ravichandran",lastname: "Ashwin",type:"bowler"}   
  6. ];   
  7. var batsman = players.filter(function (ele) {   
  8. return (ele.type==='batsman});   
  9. //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]  

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:

  1. array.reduce(function(prevValue,curValue,index,array){   
  2. //do something   
  3. }, initialValue);  
Arguments Description
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.

  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", branch: "Developer",salary:60000},   
  3. {empName : "Ashish", branch: "Tester",salary:45000},   
  4. {empName : "Mitesh", branch: "Mobile",salary:35000},   
  5. {empName : "Avinash",branch: "Designer",salary:40000}   
  6. ];   
  7.   
  8. var salaries = empDetails.map(function(ele) {   
  9. return (ele.salary);   
  10. });   
  11. var totalSalary = salaries.reduce(function(prev, curr) {   
  12. return (prev + curr);   
  13. });   
  14.   
  15. // Or you can simplify the above code as shown below:   
  16.   
  17. var totalSalary = empDetails.map(function(ele) {   
  18. return (ele.salary);   
  19. }).reduce(function(prev, curr) {   
  20. return (prev + curr);   
  21. });   
  22. //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:

Up Next
    Ebook Download
    View all
    Learn
    View all