JavaScript’s Array Reduce

Breaking it down by iteration

Dan Nolan
ChainShot
3 min readSep 5, 2019

--

JavaScript’s Array.prototype.reduce can be a tricky function to grasp! When you look up the documentation on MDN you immediately see a reducer function which takes an accumulator and a currentValue, and sums them together. Sort of like the image below:

Visual of reducing an array for a sum

Tricky terminology aside for a second. When should you use reduce?

Use reduce when you have an array of elements you’d like to combine into a single value or object. A great example of this is sum, like you saw above! We have several numbers that we want to combine (by addition, in this case) to get one number.

The code for such a reduction may look like this:

[1,3,6].reduce((accumulator, currentValue) => {
return accumulator + currentValue;
});

Ah, there it is in the code again! That word: accumulator. What does it mean?

Quite simply, the accumulator is the value returned after each iteration of the function. Let’s break this down by iteration visually:

In the first iteration we start with the accumulator set to 1. The first element of the array is chosen as the initial value, by default. You can see that the currentValue is set to 3. Since the first element was used as the initial value, the second element in our array becomes the currentValue for the first iteration.

The first iteration sums together 3+1, returning 4. This returned value becomes the accumulator for the second iteration. The second iteration also moves forward in the array to grab the next element and set it as the currentValue. The second iteration sums together 6 + 4, returning 10. If there was another iteration after this, 10 would be the next accumulator. This would keep going even in a much bigger array. However, since this is the final element in the array it is simply the final reduced value.

Reducing many elements to one

Another example of using reduce might be to find the largest number in the array. In that case, instead of using the addition operator, we would compare the two numbers and return the larger one for the accumulator after each iteration. Let’s see how this might look in code:

[1,3,6].reduce((accumulator, currentValue) => {
return accumulator > currentValue ? accumulator : currentValue;
});

The fun doesn’t stop there either, there are plenty of great examples of using reduce to start with an array and reduce to an object!

Want to dive in to some code exercises yourself? Check out this in-browser code tutorial on Array Reduce!

Additionally here’s a video going over the exercises within the ChainShot Classroom:

Array Reduce in the ChainShot Classroom

For Tutorials and Latest Updates, follow us on Twitter! Or check out www.chainshot.com.

--

--