Decoded: JavaScript Array Methods - .map(), .filter() and .reduce()

Decoded: JavaScript Array Methods - .map(), .filter() and .reduce()

The .map, .filter and .reduce methods are high-order functions (functions that accept functions as parameters and/or returns a function) that loop through an array and apply the conditions of a callback on each element before returning a new array.

Let's take a look at the map method first 👇

.map()

Map overview.png

When using the map method, the callback function takes one required argument and two optional ones:

  1. The current value of the element - required
  2. The index of the element - optional
  3. The whole array - optional

These arguments must be passed to the function in this order.

Map example.png

The function conditions are then called on every element of the array.

In this example, the map method is used on the ‘numbersToFive’ array, and multiplies each element by it by itself, and returns the output to a new array.

Note: this example only uses the required argument (currentValue).

.filter()

Filter Example.png

The filter method uses the same function arguments as map (note: we're only using currentValue again here).

Here, it checks the numbersToFive array to see if each element divides by two with no remainders (using %).

The values that meet this condition are output to a new array.

Filter Example 2.png

Another use case for the filter method is to return all the elements of an array with the same data type.

Here, the filter method is used to loop through the ‘dataTypes’ array, and return only the elements that have the data type of ‘number’.

.reduce()

The reduce method is slightly different from the previous two.

While it does still take the current value, index and whole array as arguments, it also takes the accumulator argument, which must come first in the list of function arguments.

Reduce Parameters.png

The reduce method loops through the array and returns the function’s accumulated result.

In the example below, we loop through the numbersToFive array, and add the value of each element to the accumulator.

Reduce Example.png

There is one more unique feature of the reduce method, which is that we can set the value the accumulator starts at.

Here, the initial value has been set as 100 (following the function). When the elements of the array are added to the accumulator, the accumulator begins at 100.

Initial Value.png

Conclusion

Does this article cover all of the uses of map, filter and reduce? No. These methods are very powerful and open up a lot of possibilities within JavaScript.

You can find further reading on these methods here:

Map:

Map - MDN Docs

Map - W3Schools

Map - freeCodeCamp

Filter:

Filter - MDN Docs

Filter - W3Schools

Filter - freeCodeCamp

Reudce:

Reduce - MDN Docs

Reduce - W3Schools

Reduce - freeCodeCamp