Created
November 6, 2020 19:10
-
-
Save akhrszk/5059d03df7574601558acb90d9c2962c to your computer and use it in GitHub Desktop.
Generates array of objects grouped by key.
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
const groupBy = <K, V>(arr: readonly V[], getKey: (cur: V, idx: number, src: readonly V[]) => K): V[][] => | |
arr.reduce((acc, cur, idx, src) => { | |
const key = getKey(cur, idx, src); | |
const item = acc.find(([k,]) => k === key); | |
if (item) { | |
const [, v] = item; | |
v.push(cur); | |
} else { | |
acc.push([key, [cur]]); | |
} | |
return acc; | |
}, [] as [K, V[]][]) | |
.map(([, v]) => v); | |
export default groupBy; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment