Created
February 15, 2024 12:13
-
-
Save dominique-mueller/671dd448b57f58e12f903195a73f2dd7 to your computer and use it in GitHub Desktop.
group-by.ts
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
/** | |
* 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