Created
February 22, 2022 01:20
-
-
Save tgmarinho/25fc525b1882b6e80822bc9e368aaebf to your computer and use it in GitHub Desktop.
group by in typescript
This file contains hidden or 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
export const groupBy = <T, K extends keyof any>( | |
array: T[], | |
getKey: (item: T) => K | |
) => | |
array.reduce((acc, current) => { | |
const group = getKey(current) | |
if (!acc[group]) acc[group] = [] | |
acc[group].push(current) | |
return acc | |
}, {} as Record<K, T[]>) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment