Double Your Objects With This One Weird Trick (or, Reduce Doesn’t Exactly Mean What I Thought It Did)

Paul Galvin
2 min readSep 6, 2016

--

(update 9/26/2016: I put together a video on this topic up onto the YouTube machine: https://www.youtube.com/watch?v=eOfzpgLP3mE).

This is the 9th article in my “examples series” for functional programming. Read about the series here, including links to previous and future examples.

I was watching Mattias Petter Johansson’s quirky videos on functional programming and realized that the iconic reduce function isn’t exactly about “reducing,” at least in the everyday sense of that word. Here’s a really common definition of the function:

The reduce() method applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value.

The above comes from: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce, but you can find a similar definition almost anywhere. Or at least, I could.

Everyone seems to pair the iconic definition above to an iconic sample — reduce a collection of objects down to a single value, usually by summing up one of its properties. For instance, total up an order by iterating through a collection of order lines, multiplying price by quantity.

I think that this trivializes reduce’s “true” power. I think the definition is pretty accurate up to the last 7 words. Here’s an example where the common sense idea of “reduce” is broken:

It doesn’t look like a lot of reducing is going on here!

I initialize an array (arr) with some data — an object with two properties, field1 and field2. I then use reduce to iterate over the collection. My accumulator is the variable “prev” and it starts off as empty array. On each iteration, it concats the currently passed in object (“currentItem”) to the array twice — duplicating it.

Here’s the output from Chrome:

No, not reduced at all!

So, reduce *can* be used to reduce things down to a single value or smaller set of values. Several blog posts in this series do exactly that. But it doesn’t really need to “reduce” at all.

At the end of the day, reduce iterates over your collection and executes some logic during each iteration. The result of that logic (what you return) is available to the logic during the next iteration as an input parameter. That logic might condense the data down to a simple scalar or some other object, or as you can see in the example, expand upon it.

Happy programming!

</end>

--

--

Paul Galvin

Author and Practice Director @ Neudesic/IBM. Father, Not-Great-But-Always-Trying Zen Buddhist. “Yet Another TypeScript Book” (https://amzn.to/2ABntAX).