Skip to content

Instantly share code, notes, and snippets.

@dominique-mueller
Created February 15, 2024 12:13
Show Gist options
  • Save dominique-mueller/671dd448b57f58e12f903195a73f2dd7 to your computer and use it in GitHub Desktop.
Save dominique-mueller/671dd448b57f58e12f903195a73f2dd7 to your computer and use it in GitHub Desktop.
group-by.ts
/**
* Group array by item into object
*
* Polyfill for <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/groupBy>
* Inspired by <https://stackoverflow.com/questions/14446511/most-efficient-method-to-groupby-on-an-array-of-objects#answer-64489535>
*/
export const groupBy = <T>(array: Array<T>, predicate: (value: T, index: number, array: Array<T>) => string) =>
array.reduce(
(acc, value, index, array) => {
(acc[predicate(value, index, array)] ||= []).push(value);
return acc;
},
{} as { [key: string]: Array<T> },
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment