An artcile by James Sinclair about reduce in JavaScript. Reduce is the Swiss-army knife of array iterator. It’s really powerful. So powerful, you can build most of the other array iterator methods with it, like .map(), .filter() and .flatMap().
Reduce is one of the most versatile functions that was ever discovered.
Why does reduce() cause people so much trouble?
Getting used to the idea of an initial value is a non-trivial step. And then the reducer function also has a different signature. It takes an accumulator value as well as the current array element. So learning .reduce() can be tricky because it’s so different from .map() and .filter().
Some interesting things we can do with reduce So, what interesting things can we do then?:
- Convert an array to an object
- Unfold to a larger array
- Make two calculations in one traversal
- Combine mapping and filtering into one pass
- Run asynchronous functions in sequence
Plenty of code examples in this excellent resource which will teach you more advanced uses of reduce(). Nice one!
[Read More]