Skip to content

Instantly share code, notes, and snippets.

@tgmarinho
Created February 22, 2022 01:20
Show Gist options
  • Save tgmarinho/25fc525b1882b6e80822bc9e368aaebf to your computer and use it in GitHub Desktop.
Save tgmarinho/25fc525b1882b6e80822bc9e368aaebf to your computer and use it in GitHub Desktop.
group by in typescript
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