MAP and FILTER Methods In JavaScript

Alireza Azari
3 min readNov 14, 2020

--

Sometimes, we need to transform each of the elements of an array and include the result in the new array. Basically, in order to do this, we first create an empty array then use for loop to iterate over the array elements and transform each element and then push the result to that empty array. However, it is also possible to use other new methods to achieve this goal.

MAP Method

JavaScrip in the ES5 version introduced the MAP() method that allows you to transform the array elements in a better way.

Suppose that you have an array of numbers as follows:

let numbers = [3,1,4,3,2];

And you need to multiply each number(element of the array) to 2.

You can simply use the map() method to return a new array containing the results of applying an operation on all original array of elements.

Using the map() method to transform each element of the array

Alternatively, you can also use the arrow function to get the same result:

Using the arrow function in the map() method

In fact, the map() method calls a Callback function on every element of an array and returns a new array that contains the results.

Let’s see another example to better understand the functionality of this method :

Suppose we have an array of amounts in our bank account, we want to know what amounts are part of the deposits and what amounts are part of the withdrawals:

Output

In this example, it is the map method that will call the function for each of the array elements in the movement array. Now each time that the map method calls it will simply pass in the current array element as well as the current index in the whole array.(mov=current element and i=current index)

FILTER Method

The filter() Array method checks the condition and creates a new array with new elements that fall under given criteria from an existing array.

Let’s take a look at this example:

the output is : [3,4,3]

Alternatively, you can also write this in 2 different ways while you get the same result:

--

--

Alireza Azari
Alireza Azari

Written by Alireza Azari

Freelance Front-end Developer

No responses yet