Created
October 7, 2016 18:45
-
-
Save arturparkhisenko/424ce77b82dd5de89902bb29c477edea to your computer and use it in GitHub Desktop.
js-reduce-vs-filter-and-map, Use reduce instead of chains map and filter, to reduce the number of repeated passes through the array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://twitter.com/forwebdev/status/782844763942817792 | |
const users = [{ | |
firstName: 'John', | |
lastName: 'Black', | |
age: 27 | |
}, ...]; | |
// bad, two passes | |
users | |
.filter(user => user.age < 40) | |
.map(({firstName, lastName}) => `${firstName} ${lastName}`); | |
// -> ['John Black', ...] | |
// good, one pass | |
users.reduce((acc, user) => { | |
if (user.age < 40) { | |
return acc.concat(`${firstName} ${lastName}`); | |
} | |
},[]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment