Skip to content

Instantly share code, notes, and snippets.

@sirmews
Forked from ramsunvtech/groupBy.js
Created May 22, 2019 02:10
Show Gist options
  • Save sirmews/21a4d33cb1abd7a808cd7ff02df85e5b to your computer and use it in GitHub Desktop.
Save sirmews/21a4d33cb1abd7a808cd7ff02df85e5b 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