logoalt Hacker News

marctatoday at 5:37 AM3 repliesview on HN

Why is arr.filter().map() better than arr.reduce()? Doesn't arr.reduce() only loop once through the array?


Replies

ematoday at 6:54 AM

For me it's about the speed of understanding what the code does. Because filter and map are very constrained in what they can do they quickly tell me a lot about the shape of the computation I'm working with. In contrast reduce is much more flexible and so I need to do a much more detailed analysis to just answer a basic question like "is the result a scalar or another collection?".

FlameWolftoday at 5:54 AM

Exactly. If I need just filter/map/some etc., I use it. But if I need a combination of more than one, that's a job for reduce().

QuercusMaxtoday at 6:06 AM

Chained filter and map don't necessarily iterate multiple times. They certainly can but depending on how things are built they very often run as a single loop with the operations chained.