typescript-book
typescript-book copied to clipboard
A nice typesafe groupBy / partition function
https://twitter.com/SeaRyanC/status/1179816663199277056 :rose:


Extracted for easier copy/paste:
function partition<T, U extends string>(
arr: ReadonlyArray<T>,
sorter: (el: T) => U
) {
const res = {} as { [K in U]: T[] | undefined };
for (const el of arr) {
const key = sorter(el);
const target: T[] = res[key] ?? (res[key] = []);
target.push(el);
}
return res;
}