Use map (), filter (), and reduce () in JavaScript

Tram Ho


When working with arrays in javascript , you’ve probably worked with one of the map , filter or reduce methods.

And when learning about these methods is a bit complicated, each function has different functions. So in this article I will show the use and use of these functions in certain contexts.

When working with arrays , when running a loop to manipulate the elements in the array, 95% of the time we will manipulate the data similar to the way these 3 functions work, it will: map each element in array into another value, filter the array into smaller arrays, or reduce the array into a single value . Let’s find out.

Explain the functions

Map ()

The .map () method is used when you want to manipulate an array and want to return an array of values ​​that change based on the value of the input array.

Let’s look at an example of the calculation that returns the area of ​​a square based on the length of the edge

We can quickly get the area of ​​the returned area with easier to understand code as follows:

map () takes an input callback function that transforms each element in the array into a new value.

Filter ()

With .filter (), this function is used to create a subset of the set, and only those that satisfy the condition are included in the subset.

Let’s look at the example below, we will filter the odd number elements (divided by 2 remainder 1) from the input array.

Similarly, .map, .filter receive a callback function to filter elements from the original array, which will meet the criteria will be included in the result array.

Reduce ()

Finally, the .reduce () function is the most difficult function if you don’t know how to use it. The name of the function indicates that we reduce the number of elements in the array to a single value. If this function was called build up , it would probably be less misleading than reduce .

This function accepts an initial value of the output, then iterates for each element in a formula (similar to .map ()), and then adds the value to the output. This is a case where we accrue to calculate the amount raised for charity as follows:

Unlike .map () and .filter (), the .reduce () function requires an input parameter to be a callback function (with two parameters: the accumulated value (accumulator) and the value of the current element ( current value)), the second parameter is the starting value of the output (yes or no, otherwise the default value is 0).


So we have learned through the 3 functions commonly used to manipulate arrays in Javascript, they not only make our code shorter but also help the code to be readable and easier to understand. Thanks for reading.

Any fool can write code that a computer can understand. Good programmers write code that humans can understand.

The article references

Share the news now

Source : Viblo