DEV Community

The beast that is Array.prototype.reduce

Akshendra Pratap Singh on June 23, 2018

reduce() is an absolute beast of a method when it comes to functional style programming in JavaScript. The more you use it, the more you see use ca...
Collapse
 
malcolmkee profile image
Malcolm Kee

You can use reduce to implement map, filter, etc. That's why some people call reduce as the most important operation of array.

Besides, just to add on, your example of reducing to a boolean can be replaced with Array.prototype.some method.

Collapse
 
kayis profile image
K

Yes, reduce is actually an important building block of FP.

Collapse
 
akshendra profile image
Akshendra Pratap Singh

Thanks for reminding me about .some(). I always forget that it exists.

Collapse
 
itsasine profile image
ItsASine (Kayla)

Methods like reduce and map always confuse me because the documentation is ultra simple (like summation) while the tech community adores them for being powerful and versatile...

Your post was the first I've seen to approach it with practical examples while still being approachable to someone learning it for the first time. Great post!

Collapse
 
tompearson profile image
Tom Pearson

I'm a big fan of reduce but there's often a simpler solution, or at least one which makes for more legible code. For example you can flatten an array of arrays using concat and restructuring e.g.

const a = [[1,2,3,4,5],[1,2,3,4,5]];

const flattened = [].concat(...a);
// flattened will be ... [1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

As a general policy I try to name my reducer function arguments to reflect what they're doing in the specific case rather than just giving them general names (as you do in your examples i.e. map vs acc for the 'previousValue' argument).