How to use Filter, Map, and Reduce in JavaScript!

Valentin Placido
2 min readAug 30, 2020

To begin with the methods filter, map, and reduce are different ways to manipulate data found in an array.These three methods have become very popular to use instead of using traditional methods of traversing arrays like for or while loops. So in this post I will go over the basics of each method and when is the best time to use each one.

Filter

Filter should be used when you would want to refine the data from an array given a conditional statement. Below is an example of a simple application of the filter method:

let arr = [5, 3, 10, 19, 32, 2]
let filteredArr = arr.filter(num => num > 9)
console.log(filteredArr)
//[10, 19, 32]

As we can see the filter method is simple and a quick way to refine an array next we will. cover the Map method.

Map

Map should be used when you want to perform the same operation on every element found in an array but by using map it will return a new array with the altered elements. Map functions similar to the filter method where it requires a callback function followed by instructions on what to do to every element in the array. Here is an example of the Map function:

let arr = [4, 8, 16, 24, 32]
let mapArr = arr.map(num => num/2)
console.log(mapArr)
// [2, 4, 8, 12, 16]

Map is also very simple to use and a great alternative to a for loop, next we will cover the final method Reduce.

Reduce

Reduce should be used when you want to minimize various values to a single value. Below is an example of using the reduce method:

let arr = [{
name: "john",
testScore: 89
},
{
name: "wendy",
testScore: 99
},
{
name: "sam",
testScore: 60
}
]
let reduceArr = arr.reduce((prev, val) => prev + val.testScore, 0)
console.log(reduceArr)//248

--

--