Created
May 28, 2021 03:50
-
-
Save RodrigoNovais/cb8a3f9e62f71465b762b3e105ebe35e to your computer and use it in GitHub Desktop.
This file contains 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
/** | |
* Group array of objects by given keys | |
* | |
* @param keys keys to be grouped by | |
* @param array objects to be grouped | |
* | |
* @returns an object with objects in `array` grouped by `keys` | |
*/ | |
export const groupBy = <T>(keys: (keyof T)[]) => (array: T[]): Record<string, T[]> => { | |
return array.reduce((objectsByKeyValue, obj) => { | |
const value = keys.map((key) => obj[key]).join('-'); | |
objectsByKeyValue[value] = (objectsByKeyValue[value] || []).concat(obj); | |
return objectsByKeyValue; | |
}, {} as Record<string, T[]>); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment