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.
- 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);
-
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.
- 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 implementation | JavaScript functional approach |
Code line #1,#2,#3 is required | filter() calculate automatically |
Code line #4 make use of if 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.
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){
-
- },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) |
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);
- });
-
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}
- ];
- var firstNames=players.map(function(ele){
- return (ele.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){
-
- },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.
- var numbers=[1,2,3,4,5,6,7,8,9,10];
- var evenNum=numbers.filter(function(ele){
- return ((ele%2)== 0);
- });
-
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});
-
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);
- });
-
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){
-
- }, 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.
- var numbers = [1,2,3,4,5];
- var sum=numbers.reduce(function(preValue,curValue){
- return (preValue+curValue);
- });
-
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);
- });
-
-
-
- var totalSalary = empDetails.map(function(ele) {
- return (ele.salary);
- }).reduce(function(prev, curr) {
- return (prev + curr);
- });
-
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: