typestar

Group entries by value in TypeScript

Groups object entries by their value.

function invert<K extends string, V extends string>(
  record: Record<K, V>,
): Record<V, K[]> {
  const out = {} as Record<V, K[]>;
  for (const [key, value] of Object.entries(record) as [K, V][]) {
    (out[value] ??= []).push(key);
  }
  return out;
}

Keywords and builtins used here

The run, in numbers

Lines
9
Characters to type
240
Tokens
92
Three-star pace
105 tpm

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

Type this snippet

Step 4 of 11 in Generic helpers, step 12 of 20 in Generics.

← Previous Next →