Skip to content

Instantly share code, notes, and snippets.

@Alexgalinier
Created September 25, 2017 06:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Alexgalinier/b068a7f0730b339f078b434ea6ac5647 to your computer and use it in GitHub Desktop.
Save Alexgalinier/b068a7f0730b339f078b434ea6ac5647 to your computer and use it in GitHub Desktop.
Filter an array of people by age and group them by gender.
function filterAndGroup(data, filterFunc, groupByKey) {
return data.reduce((acc, item) => {
if (filterFunc(item)) {
if (item[groupByKey] in acc) {
acc[item[groupByKey]].push(item);
} else {
acc[item[groupByKey]] = [item];
}
}
return acc;
}, {});
}
function filterBy30to40AndGroupByGender(data) {
return filterAndGroup(
data,
(_) => _.age > 30 && _.age < 40,
'gender'
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment