How it works...

Like other methods we've seen previously, the reduce method visits each element in an array. However, it takes a different set of parameters. The first parameter is a function that receives two arguments, an accumulator and the current element. The result of this function is the new accumulated value.

The second argument is the initial value of the accumulator.

In the recipe, the accumulator is initialized as an empty object. The function then uses the current array value as a key and increments a counter for that key. In this way, we count the number of times each key appears.

We can see that, unlike with map, the resulting data shape is different from the initial array.

Get ECMAScript Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.