Skip to content

Instantly share code, notes, and snippets.

@akhrszk
Created November 6, 2020 19:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akhrszk/5059d03df7574601558acb90d9c2962c to your computer and use it in GitHub Desktop.
Save akhrszk/5059d03df7574601558acb90d9c2962c to your computer and use it in GitHub Desktop.
Generates array of objects grouped by key.
const groupBy = <K, V>(arr: readonly V[], getKey: (cur: V, idx: number, src: readonly V[]) => K): V[][] =>
arr.reduce((acc, cur, idx, src) => {
const key = getKey(cur, idx, src);
const item = acc.find(([k,]) => k === key);
if (item) {
const [, v] = item;
v.push(cur);
} else {
acc.push([key, [cur]]);
}
return acc;
}, [] as [K, V[]][])
.map(([, v]) => v);
export default groupBy;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment