Do you understand JavaScript’s reduce method?

Tram Ho


reduce is a rather confusing method, and there are a lot of confusing explanations floating around on the internet. This is an extremely effective method and will bring a lot of benefits if we can understand it. Typical is reduce frequently used in state management tools, typically redux.

A typical use of method reduce in JavaScript:


reduce derived from 2 terms Reducer and Accumulatoraccumulator is the result, and reducer is the action we take to achieve that result.

One thing to remember is reducer returns one and only one value (Because its name is reduce but ).

See a good example:

The above code will return 60 (10 + 20 + 30). In this case we can use reduce to not mutate the value of the variable value.

The code below will also return 60, however won’t mutate the edge value ours (we’ll call it initialValue):

The above code can look a bit confusing, right? To see how the reduce function is running, we put console.log into function reducer Please:

Open the console and we will see the following log:

The first thing we will see will be the function reducer will run 3 times equivalent to 3 elements of the array numbers. Our Accumulator (Total) will start from 0, this is also the initial value initialValue passed to method reduce.

The last run of the method will have sum with a value of 30, and number is 30, so the result is 30 + 30 = 60. This is also the result of method reduce our.

Here is a simple example of how to use method reduce, In the following, we will try to apply it to other more complex examples.

Flatten an Array using Reduce

For example we have the following array:

We can use method .flat of JavaScript is always okay, right? Suddenly, one fine day, JavaScript removed that function. So I try to rewrite it myself with reduce Please.

We will write a function like this to flatten all arrays, no matter how deep it is:

Try it with arrays numbers Above, we get the following result:

Let’s try another example:

Changing Object structure

For example, the server returns a list of coins as follows:

And we need to change to an object like this:

To do that, we need to write a function like this:

When running, we will have the following output:


When you first learn, maybe method reduce will be slightly more confusing and difficult to access than some of the other methods of Array as map or filter, but just by understanding the concept, syntax and use-case, it can become an extremely effective tool in our hands.

Share the news now