TypeScript

groupBy (with key callback)

admin by @admin ADMIN
Jun 17, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Group a list into a record keyed by whatever the callback returns. Like Lodash _.groupBy or the new Object.groupBy in modern runtimes. Generic enough to handle string, number, or symbol keys.
TypeScript
Raw
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] }
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.