Newsletter

JavaScript reduce(): how the array method actually works

JavaScript reduce(): how the array method actually works
In this article I explain how to use the JavaScript reduce method, with examples showing how it works and when to reach for it.
The JavaScript reduce method applies a function to every item of an array to reduce that array to a single value.
Here is an example:

javascript
let result = array.reduce((acc, v, i, a) => {
// returns the new value to the variable 
}, initVal);

// result - the single value that is returned.
// array - the array the reduce function runs on.
// acc - the accumulator, which builds up every returned value.
// v - the current value being processed
// i - the index of the value being processed.
// a - the original array
// initVal - an optional initial value.
// If no initial value is supplied,
// item 0 is used as the initial value.

The JavaScript reduce method can be thought of as a for loop built specifically to take the values of an array and turn them into something new. Take a look at this example.

php
var array = [11, 12, 13, 14];
var sum = 0;
for(var i = 0; i  < array.length; i++) {
      sum += array[i];
 }

// sum = 50

The point of the code above is to find the sum of every value in our array. It works, but there is a simpler way to get the same result.

Let us refactor that function with the JavaScript reduce() method.

javascript
let array = [11, 12, 13, 14];
let sum = array.reduce((bcc, v) => bcc + v);
// sum = 50

Same result, no loop in sight.

We used the variable bcc to carry the running total. As reduce() walks through the array, the bcc value grows until the function is done.

Remember I mentioned we could pass an optional initial value? It is easy enough to set up. We will take the same example as before: we add our array up, but this time we want to start from an initial value of 250.

What does it look like when we start from 250? The example below says it all.

javascript
let array = [11, 12, 13, 14];
let sum = array.reduce((bcc, v) => bcc + v, 250);

As you can see, the code above is almost identical to the previous example. The only change is the second argument after our callback: I passed the number 250 as the starting point. Now, when we run the function, the sum comes to 300.

I hope this helps. There are several other articles here on JavaScript, and on JavaScript arrays in particular, such as this one on how to merge two JavaScript arrays.

JavaScript

Damien Flandrin Web developer since 2010, creator of Gekkode and Email Impact. Every article is tested on a real project before publication. Contact
Newsletter

New tests, tutorials and projects, by e-mail.

Reproducible tests, versioned code, dated results. Never any spam.