Skip to content

Instantly share code, notes, and snippets.

@RodrigoNovais
Created May 28, 2021 03:50
Show Gist options
  • Save RodrigoNovais/cb8a3f9e62f71465b762b3e105ebe35e to your computer and use it in GitHub Desktop.
Save RodrigoNovais/cb8a3f9e62f71465b762b3e105ebe35e to your computer and use it in GitHub Desktop.
/**
* 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