Files
php_xcstat/src/global/tools.ts
2022-12-05 19:04:39 +01:00

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;
}