JavaScript Map, Filter And Reduce

Introduction

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 reduce the complexity of the code and make the code more readable.

Traditional Approach

The code snippet which is an implementation of a for loop, traverses over the elements of an array and inserts the non-duplicate elements into 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 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
numbers.push(numbers[i]) new number is an array which stores the non-duplicate entries

The above implementation can be done by making use of the 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 is 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 makes use of if the condition filter() does not require any if-block
Code line #5 where numbers must be a list or an array, their data type is checked filter() does not require to checking 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);
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 the 'thisValue' parameter is provided, it will be used as ‘this’ for each invocation of a callback function.If this parameter is empty then the value ‘undefined’ will be passed as its ‘this’ value. (Optional)

The following sample, examples show the 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 (ele * ele);
});
//output: square=[1,4,9,16,25]

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

var players = [
    {firstname: "Sachin", lastname: "Tendulakar", Age: 42},
    {firstname: "Virat", lastname: "Kohli", Age: 27},
    {firstname: "Yuvraj", lastname: "Singh", Age: 34}
];
var 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 returns those elements that 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 show 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 a 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);
Arguments Description
prevValue The value which is previously returned in the last invocation of the callback function. (Required)
curValue The current value is 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.

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.

Read more articles on JavaScript