Skip to content

Instantly share code, notes, and snippets.

@lffg
Last active November 26, 2021 19:49
Show Gist options
  • Select an option

  • Save lffg/d9a814d4c3903906c47f319674211110 to your computer and use it in GitHub Desktop.

Select an option

Save lffg/d9a814d4c3903906c47f319674211110 to your computer and use it in GitHub Desktop.
const data = [
{ key: 'a', val: 'foo' },
{ key: 'b', val: 'bar' },
{ key: 'c', val: 'baz' },
{ key: 'a', val: 'qux' },
{ key: 'b', val: 'quxx' }
];
function groupBy(key, arr) {
const result = {};
for (const el of arr) {
const group = result[el[key]] ??= [];
group.push(el);
}
return result;
}
console.log(groupBy('key', data));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment