.reduce is the swiss army knife of all js array methods, it's my favourite. Your readability takes a bit of a hit, so I try not to be too convoluted with it, but it is always really fun to flex its muscles every now and again.
If you find yourself chaining array methods .reduce can almost always do the work of 2 or more of them at once.
Reduce should really only be used for "accumulation" operations. Sneakily doing other things with it only serves to make code misleading and confusing.
Edit
So, reduce use-cases:
Intended: accumulating a value type, i.e. binary operator folding
Not: Associating a mutable object/state with each element, instead use each_with(obj) that some languages have, or just a normal loop
9
u/[deleted] Feb 27 '20
.reduceis the swiss army knife of all js array methods, it's my favourite. Your readability takes a bit of a hit, so I try not to be too convoluted with it, but it is always really fun to flex its muscles every now and again.If you find yourself chaining array methods
.reducecan almost always do the work of 2 or more of them at once.