export function groupBy<T, K extends PropertyKey>(
items: readonly T[],
by: (item: T) => K,
): Record<K, T[]> {
const out = {} as Record<K, T[]>;
for (const item of items) {
const k = by(item);
(out[k] ??= []).push(item);
}
return out;
}
const users = [
{ name: 'Alice', team: 'A' },
{ name: 'Bob', team: 'B' },
{ name: 'Cara', team: 'A' },
];
const byTeam = groupBy(users, u => u.team);
// { A: [Alice, Cara], B: [Bob] }
Create a free account and build your private vault. Share publicly whenever you want.