Skip to content
GreenSnippets

Generic groupBy with key inference

Group an array into a Record by a property or function while keeping the item type.

TypeScript
function groupBy<T, K extends string | number>(
  items: readonly T[],
  getKey: (item: T) => K,
): Partial<Record<K, T[]>> {
  const result: Partial<Record<K, T[]>> = {};
  for (const item of items) {
    const key = getKey(item);
    (result[key] ??= []).push(item);
  }
  return result;
}

Example / expected output

Output
const byRole = groupBy(users, (u) => u.role);
// Partial<Record<"admin" | "member", User[]>>

How it works

The key function decides the group name, and the return type is a partial record because not every possible key necessarily appears. Object.groupBy exists in newer runtimes, but this version works everywhere and is easy to extend.