Last active
October 28, 2023 12:09
-
-
Save vyspiansky/3705db9c8a4e79532c09392aca011ee7 to your computer and use it in GitHub Desktop.
TypeScript groupBy function
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 an array of objects by object property | |
*/ | |
const groupBy = <T>(array: T[], key: keyof T): { [key: string]: T[] } => { | |
return array.reduce((accumulator: { [key: string]: T[] }, currentElement: T) => { | |
const keyValue = currentElement[key] as unknown as string; | |
if (keyValue in accumulator) { | |
accumulator[keyValue].push(currentElement); | |
} else { | |
accumulator[keyValue] = [currentElement]; | |
} | |
return accumulator; | |
}, {} as { [key: string]: T[] }); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment