Difference between map, filter and reduce in JavaScript

I’ve seen a lot of JS beginners struggle when using map, filter or reduce and don’t know the different use cases of each of these methods. So I decided to write this blog and compare these methods with a few examples.

Let’s jump right into it.

Array.prototype.filter()

The filter method is called on an array and returns a new array and selects the elements that satisfy a certain condition.

function useFilter(arr) {
return arr.filter((element) => {
// You have to return a boolean here.
return element % 2 === 0
})
}
useFilter([1, 2, 3, 4, 5]) // return [2, 4]

In the example above the condition is element % 2 === 0. Therefore only even numbers satisfy this condition which are 2 and 4 in the example above.

Array.protoype.map()

The map method is used when we want to change each element inside of an array and then return a new array containing the new elements.

function doubler(arr) {
return arr.map((element) => {
return element * 2
})
}
doubler([1, 2, 3]) // returns [2, 4, 6]

The simple function above returns a new array in which all the elements are doubled.

Array.protoype.reduce()

The reduce methods is more advanced than the previous two methods. It has an accumulator which can be of any type and is remembered throughout the whole loop and it can be modified in each iteration and is finally returned at the end.

Genreal syntax

Array.protoype.reduce((accumulator, currentValue) => {}, initialValue)

Examples

First example is a function that returns the sum of all the elements in array.

function getSum(arr) {
return arr.reduce((acc, currVal) => {
// Whatever you return here will be the new value of the accumulator
return acc + currVal
}, 0)
}
getSum([1, 2, 3]) // returns 6

In order to understand this better, let’s keep track of all our variables throughout the whole loop.

iteration    acc    currVal    retrun value
1st 0 1 0 + 1 (1)
2nd 1 2 1 + 2 (3)
3rd 3 3 3 + 3 (6)

In the next example I want to use an empty array as the initialValue to mimic the functionality of filter() method just to show you the power of reduce().

function useReduceToFilter(arr) {
return arr.reduce((acc, currVal) => {
currVal % 2 === 0 && acc.push(currVal)
return acc
}, [])
}
useReduceToFilter([1, 2, 3, 4]) // returns [2, 4]

Let’s keep track of all our variables one more time.

iteration    acc    currVal    retrun value
1st [] 1 []
2nd [] 2 [2]
3rd [2] 3 [2]
4th [2] 4 [2, 4]

Hope this was helpful. Should you have any questions let me know in the comments and I’ll answer them to the best of my knowledge.

Happy coding