Skip to content

Instantly share code, notes, and snippets.

@slavo23
Last active March 24, 2021 13:38
Show Gist options
  • Select an option

  • Save slavo23/426b565bc2422fed11c4d0b19361ad26 to your computer and use it in GitHub Desktop.

Select an option

Save slavo23/426b565bc2422fed11c4d0b19361ad26 to your computer and use it in GitHub Desktop.
GroupBy for typescript
interface IGroupedElements<T> {
[value: string]: T[]
}
const groupBy = <T, U>(collection: T[], predicate: (elem: T) => U): IGroupedElements<T> => {
return collection.reduce((accumulator, current) => {
const output = predicate(current).toString()
if (output in accumulator) {
accumulator[output].push(current)
} else {
accumulator[output] = [current]
}
return accumulator
}, {})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment