Created
October 6, 2023 15:58
-
-
Save olibooty/febbad88822445e84f2ee479cd6316cc to your computer and use it in GitHub Desktop.
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
| /** | |
| * Groups elements in an array by a given key (if that key exists within each | |
| * iteratee) | |
| * | |
| * *Optional: you can provide a getter function to access a value within each | |
| * item of the array* | |
| */ | |
| const groupBy = <T extends Record<string, any>, U = T[keyof T]>( | |
| key: keyof T, | |
| array: T[], | |
| getter?: (arg0: T) => U | |
| ) => { | |
| let output: Record<PropertyKey, (T | U)[]> = {}; | |
| for (const element of array) { | |
| if (key in element) { | |
| const value = element[key]; | |
| const previousState = output[value] || []; | |
| const elementToAdd = getter ? getter(element) : element; | |
| output[value] = [...previousState, elementToAdd]; | |
| } | |
| } | |
| return output; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment