Skip to content

Instantly share code, notes, and snippets.

@onosendi
Last active January 24, 2022 21:24
Show Gist options
  • Select an option

  • Save onosendi/509e387003b59d2f3fdfba75c3dfd2da to your computer and use it in GitHub Desktop.

Select an option

Save onosendi/509e387003b59d2f3fdfba75c3dfd2da to your computer and use it in GitHub Desktop.
`groupBy` function
const o = [
{ name: 'Bobby', group: 1 },
{ name: 'Jimmy', group: 2 },
{ name: 'Tommy', group: 1 },
];
function groupBy(arr, key = 'group') {
const map = arr.reduce((acc, curr) => ({
...acc,
[curr[key]]: [...(acc[curr[key]] || []), curr],
}), {});
return Object.values(map);
}
const z = groupBy(o);
console.log(z);
// [
// [ { name: 'Bobby', group: 1 }, { name: 'Tommy', group: 1 } ],
// [ { name: 'Jimmy', group: 2 } ]
// ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment