.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
I agree in general (which I said in my post) but also generally try not to follow arbitrary rules like that.
I never do anything 'sneakily'. If a one line comment will save an extra loop or 2 through an array, especially if the size of which is unknown, I'll make the case for .reduce any day.
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.