Map, Filter, Reduce in Javascript


Overview

 .map(), .filter(), .reduce() are all array methods in javascript. Each method will iterate over an array and perform transformations or computation. Each will return a new array based on the result of the function. Lets see how to use each of these methods in this article.

Map :

The map() is a method that transforms an array according to the applied function and returns the updated output. It works on each element of an array. 

Syntax :

 array.map(callback[,object])

Example 1 

Double each elements in an array.: 

Example 2:

Binary of each element in an array:

Filter:

The filter() method takes each element in an array and it applies a conditional statement against it. If the conditional returns true, it will get pushed into an output array , else it will not.

Example 1:

Find odd numbers in an array.

Example 2:

Numbers greater than 4 in array

The syntax of filter() is similar to map(), except the callback function should return true to keep the element or not 

Reduce:

The reduce() method reduces an array of values down to just one value. It runs a reducer function on each element of the array to get the output value.

Example 1:

Sum of the array:

Example 2:

Find maximum number in an array

Conclusion:

We can try to replace some of our for loops with .map(), .filter(), .reduce() where it seems to fit. The code will become much easier to read.

Leave A Comment

Your email address will not be published. Required fields are marked *