Comment by marcta
10 hours ago
Why is arr.filter().map() better than arr.reduce()? Doesn't arr.reduce() only loop once through the array?
10 hours ago
Why is arr.filter().map() better than arr.reduce()? Doesn't arr.reduce() only loop once through the array?
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?".
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().
So you prefer
over
The only advantage of the reduction as I see it is performance, but this is highly dubious and would need to be profiled for proof (I don't recall seeing removing a pass like this matter in practice). And if perf does matter, a for..of loop would be clearer and one-pass, not to mention async-compatible:
Exercises like this illustrate why verbal technical job interviews are useful in the age of LLMs--a series of A/B taste preferences seems high signal and ripe for discussion: "Ah, so you're choosing reduce for perf... please describe a scenario you encountered where this made a measurable impact".
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.