JavaScript Array.reduce()

Jeff Lowery
HackerNoon.com
4 min readApr 21, 2019

--

How do I loathe thee? Let me count the ways…

The Array.reduce() method has been around awhile. Like map(), filter() and find(), it operates upon an array of values by invoking a callback function.

Here’s an example from the developer.mozilla.org site:

Seems straightforward, right? On with the grievances:

0. It doesn’t do what you expect

Let’s look at this again:

Now I’ll modify the reducer function to add 1 to each value of the array, then sum it with the previous value. Since I’m adding 1 to four array elements, I expect to get a sum of 14.

Hold on… what?

Turns out the first element of the array is the initial accumulator value. So, instead of

It is actually:

All those reduce examples online that use a sum function as illustration can mislead you. You can get to the right answer, of course: just add an accumulator initial value as a second argument to the reduce method:

1. It’s misnamed

The name reduce would lead one to believe that it reduces an array of element to a subset of those elements. That’s not really what it does. It can do the opposite of reduce, in fact:

And it doesn’t even have to return an array:

2. The order of callback arguments is weird

Let’s compare the callbacks of map(), filter(), find(), and reduce():

map: (currentValue, index, array, this) => {}

filter: (currentValue, index, array, this) => {}

find: (currentValue, index, array, this) => {}

reduce: (accumulator, currentValue, index, array) => {}

Your callback will get the accumulator as the first argument, not the currentValue; also, there is no parameter that takes a this argument.

3. Error: myVar.reduce is not a function

I’ve been spoiled by lodash, which treats both arrays and objects as collections, and collections have map, find, filter, and reduce methods. Not so JavaScript reduce:

As Dana Carvey used to say, “Nope, not gonna do it. Wouldn’t be prudent.” (Yes, I am that old.)

You can still do something like this, using Object.values or Object.entries:

4. Accumulator sometimes optional; results sometimes random

It’s easy to forget an initial accumulator value, even when you need one. Let’s take that above example, with one modification:

Did you notice the difference in the code? Hard to spot. What’s worse, you get an array of values back, except the first is invalid. Good thing I have tests someday!

5. Undefined? Huh?

Oh, you forgot to return the accumulator. Silly you. I never make that mistake:

You have to always return the accumulator:

So what do I recommend instead of reduce()?

I am always using Array.reduce(), and you should, too. Just know its quirks. It’s like a tiny chihuahua nipping at your heels that sometimes will get you if you’re not paying attention, but it’s mostly harmless (and far more useful than a chihuahua).

Happy reducing!

--

--

Jeff Lowery
HackerNoon.com

Wrote software for a living. Now I do it for fun.