Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Group By - ES6
function groupBy(list, props) {
return list.reduce((a, b) => {
(a[b[props]] = a[b[props]] || []).push(b);
return a;
}, {});
}
// Usage.
groupBy([{
id: 1,
group: 'user',
name: 'User #1',
}, {
id: 2,
group: 'admin',
name: 'User #2',
}, {
id: 3,
group: 'moderator',
name: 'User #3',
}, {
id: 4,
group: 'user',
name: 'User #4',
}, {
id: 5,
group: 'moderator',
name: 'User #5',
}], 'group');
/*
{admin: [], user: [], moderator: []}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment