Skip to content

Instantly share code, notes, and snippets.

@arturparkhisenko
Created October 7, 2016 18:45
Show Gist options
  • Save arturparkhisenko/424ce77b82dd5de89902bb29c477edea to your computer and use it in GitHub Desktop.
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
// 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