DEV Community

Discussion on: What s wrong with Array.reduce ?

 
wulymammoth profile image
David • Edited

Communication in a team and outside both matter. It's always about the audience and sometimes that communication means getting each other on the same page. Filter and map are less generic than reduce when maintaining the same collection data type. Reduce is typically used to "distill" or bring it down or fold the collection (array) into something else. It's much more clear to map and filter in many instances because that's exactly what we're doing -- we still want to retain the collection (array). Whereas some other operations are: "reduce to an integer/sum/max", "reduce to a different data type/object", "partition" that are better expressed as reductions that map and filter can't do.

If it's a mapping operation or filtering operation, I'd much prefer to see map or filter. If I were reviewing that code and somebody threw a reduce to do what a map or filter call does, I'd ask them why...

But generally, I see folks throwing the for-loop at map and filter operations as well -- procedural and imperative. I'd much rather the code state what it's doing (by declarative means) than have me read through the body of the for-loop to determine that what is being done is a reduction, a mapping, or a filtering operation. The for-loop is much too generic outside of small use cases.

For one place that I've worked, we always asked people to use reduce, map, and filter. If a for-loop is used, that means it's a signal to other developers that there is the possibility of early termination (not iterating across the entire collection). So we have all these use-cases broken down and documented, otherwise the for-loop can be ANY of these four operations and requires the developer to read the body of the for-loop. Accessibility is high if the audience is broad, but in a team-setting with established patterns, this is just overhead...

Thread Thread
 
dvddpl profile image
Davide de Paolis

Indeed. Early termination (or very huge datasets, where I really need/want to iterate only once) is the only case where I use for loops. Otherwise it's always map and filter + reduce sometimes.