Created
November 10, 2022 15:50
-
-
Save julien-f/dc365ca8d7ef7a0d2e610cebfc1b77a7 to your computer and use it in GitHub Desktop.
Multiple group by
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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