Skip to content

Instantly share code, notes, and snippets.

@julien-f
Created November 10, 2022 15:50
Show Gist options
  • Save julien-f/dc365ca8d7ef7a0d2e610cebfc1b77a7 to your computer and use it in GitHub Desktop.
Save julien-f/dc365ca8d7ef7a0d2e610cebfc1b77a7 to your computer and use it in GitHub Desktop.
Multiple group by
function groupBy(iterable, prop) {
const dict = { __proto__: null };
for (const item of iterable) {
const group = item[prop];
(dict[group] || (dict[group] = [])).push(item);
}
return dict;
}
export function multiGroupBy(iterable, props) {
const prop = props.shift();
const dict = groupBy(iterable, prop);
if (props.length !== 0) {
for (const key of Object.keys(dict)) {
dict[key] = multiGroupBy(dict[key], props);
}
}
props.unshift(prop);
return dict;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment