Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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