I used both methods but I am quite confused regarding the usage of both methods.
Is anything that map
can do but reduce
can not and vice ve
To understand the difference between map, filter and reduce, remember this:
Map
returns a new array with the equal no. of elements as there are in the original array. Therefore, if the original array has 5 elements, the returned array will also have 5 elements. This method is used whenever we want to make some change on every individual element of an array. You can remember that every element of ann array is being mapped to some new value in output array, therefore the name map
For eg, var originalArr = [1,2,3,4]
//[1,2,3,4]
var squaredArr = originalArr.map(function(elem){
return Math.pow(elem,2);
});
//[1,4,9,16]
Filter
returns a new array with equal/less number of elements than the original array. It returns those elements in the array which have passed some condition. This method is used when we want to apply a filter on the original array therefore the name filter
. For eg,var originalArr = [1,2,3,4]
//[1,2,3,4]
var evenArr = originalArr.filter(function(elem){
return elem%2==0;
})
//[2,4]
Reduce
returns a single value, unlike a map/filter. Therefore, whenever we want to run an operation on all elements of an array but want a single output using all elements, we use reduce
. You can remember an array's output is reduced to a single value therefore the name reduce
. For eg,var originalArr = [1,2,3,4]
//[1,2,3,4]
var sum = originalArr.reduce(function(total,elem){
return total+elem;
},0)
//10