22 lines
607 B
TypeScript
22 lines
607 B
TypeScript
export const groupBy = <T, K extends keyof any>(arr: T[], key: (i: T) => K) =>
|
|
arr.reduce((groups, item) =>
|
|
{
|
|
(groups[key(item)] ||= []).push(item);
|
|
return groups;
|
|
}, {} as Record<K, T[]>);
|
|
|
|
export function groupByMap<K, V>(list: Array<V>, keyGetter: (input: V) => K): Map<K, Array<V>>
|
|
{
|
|
const map = new Map<K, Array<V>>();
|
|
list.forEach((item) => {
|
|
const key = keyGetter(item);
|
|
const collection = map.get(key);
|
|
if (!collection) {
|
|
map.set(key, [item]);
|
|
} else {
|
|
collection.push(item);
|
|
}
|
|
});
|
|
return map;
|
|
}
|