简体   繁体   中英

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. Personally, I prefer using flatMap as I think it is easier to read, but that is entirely subjective of course. 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)?

Update: Here is an example from the referenced answer of flatMap filtering:

 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 :

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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