Last active
March 24, 2021 13:38
-
-
Save slavo23/426b565bc2422fed11c4d0b19361ad26 to your computer and use it in GitHub Desktop.
GroupBy for 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
| 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