typestar

Generic group by in TypeScript

Group by a key function, with the return type derived from the key.

function groupBy<T, K extends string>(
  items: T[],
  keyFn: (item: T) => K,
): Record<K, T[]> {
  const groups = {} as Record<K, T[]>;
  for (const item of items) {
    const key = keyFn(item);
    (groups[key] ??= []).push(item);
  }
  return groups;
}

Keywords and builtins used here

The run, in numbers

Lines
11
Characters to type
235
Tokens
88
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 50 seconds.

Type this snippet

Step 2 of 11 in Generic helpers, step 10 of 20 in Generics.

← Previous Next →