简体   繁体   English

用于映射和过滤的 FlatMap 与 Reduce - 是否推荐使用其中一种?

[英]FlatMap vs Reduce for mapping and filtering - is one recommended over the other?

According to this SO thread , flatMap or reduce are recommended when one needs to map and filter on an array of objects, especially if they want to avoid looping through the collection multiple times.根据这个 SO thread ,当需要 map 并过滤一组对象时,建议使用flatMapreduce ,特别是如果他们想避免多次循环遍历集合。 Personally, I prefer using flatMap as I think it is easier to read, but that is entirely subjective of course.就个人而言,我更喜欢使用flatMap ,因为我认为它更容易阅读,但这当然是完全主观的。 Aside from browser compatibility issues for flatMap , is one method generally recommended or beneficial over the other (perhaps because of, but not limited to, reasons of performance or readability)?除了flatMap的浏览器兼容性问题之外,一种方法是否普遍推荐或优于另一种方法(可能是因为但不限于性能或可读性的原因)?

Update: Here is an example from the referenced answer of flatMap filtering:更新:这是来自 flatMap 过滤的参考答案的示例:

 var options = [{ name: 'One', assigned: true }, { name: 'Two', assigned: false }, { name: 'Three', assigned: true }, ]; var assignees = options.flatMap((o) => (o.assigned? [o.name]: [])); console.log(assignees); document.getElementById("output").innerHTML = JSON.stringify(assignees);
 <h1>Only assigned options</h1> <pre id="output"> </pre>

Neither actually.其实也没有。 For mapping and filtering, your should use map and filter :对于映射和过滤,您应该使用mapfilter

var assignees = options.filter(o => o.assigned).map(o => o.name);

Much simpler and more readable, it directly expresses your intent.它更简单、更易读,直接表达了你的意图。 Nothing beats that on clarity.没有什么比这更清楚了。

If you care about performance, always benchmark to see the actual impact on your real-world case - but don't prematurely optimise.如果您关心性能,请始终进行基准测试以查看对您的实际案例的实际影响 - 但不要过早地进行优化。

I would use a reduce in this case.在这种情况下,我会使用减少。

 var options = [{ name: 'One', assigned: true }, { name: 'Two', assigned: false }, { name: 'Three', assigned: true }, ]; var assignees = options.reduce((results, item) => { if (item.assigned) { results.push(item.name); } return results; }, []); console.log(assignees);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM