Skip to content

Instantly share code, notes, and snippets.

@olibooty
Created October 6, 2023 15:58
Show Gist options
  • Select an option

  • Save olibooty/febbad88822445e84f2ee479cd6316cc to your computer and use it in GitHub Desktop.

Select an option

Save olibooty/febbad88822445e84f2ee479cd6316cc to your computer and use it in GitHub Desktop.
/**
* 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