Tip 26: Transform Array Data with reduce()

In this tip, you’ll learn how use reduce() to generate a new array with a different size and shape.

You’re probably tired of hearing me say that good code is predictable. But it’s true. Array methods are wonderful because you have an idea of the result at a glance without even understanding the callback function. Not only that, but array methods are easier to test and, as you’ll see in Tip 32, Write Functions for Testability, it’s much easier to write testable code than it is to add tests to complex code.

reduce()

Still, there are times when you need to create a new, radically different piece of data from an array. Maybe you need to get a count of certain items. Maybe you want to transform the array to a different structure, such as an object. That’s where reduce() comes in. The reduce() method is different from other array methods in several ways, but the most important is that it can change both the size and the shape of data (or just one or just the other). And it doesn’t necessarily return an array.

Building a reduce() function

As usual, it’s much easier to see than to explain. Here’s a reduce function that returns the exact same array. It’s useless, but it lets you see how a reduce() function is built.

Get hands-on with 1000+ tech skills courses.