Skip to content

Instantly share code, notes, and snippets.

@ramsunvtech
Created September 25, 2018 15:07
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ramsunvtech/102ac0267d33c2cc1ccdf9158d0f7fca to your computer and use it in GitHub Desktop.
Save ramsunvtech/102ac0267d33c2cc1ccdf9158d0f7fca to your computer and use it in GitHub Desktop.
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