Tip 26: Transform Array Data with reduce()
Explore the use of JavaScript's reduce() method to transform arrays by changing their size and shape. Understand how to create flexible and testable functions that extract unique values or count occurrences, enhancing your ability to write clear and efficient array manipulations.
We'll cover the following...
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.
What’s going on here? To start, notice that you pass two arguments into the
reduce() callback function on line 1: the return item (called collectedValues) and
the individual item. The return value, sometimes called the carry, is what
makes reduce() unique. It can range from an integer to a collection such as Set. ...