typestar

Unique by key in TypeScript

Deduplicates by a computed key, with the key type inferred.

function uniqueBy<T, K>(items: T[], keyFn: (item: T) => K): T[] {
  const seen = new Set<K>();
  return items.filter((item) => {
    const key = keyFn(item);
    if (seen.has(key)) return false;
    seen.add(key);
    return true;
  });
}

Keywords and builtins used here

The run, in numbers

Lines
9
Characters to type
216
Tokens
84
Three-star pace
105 tpm

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

Type this snippet

Step 7 of 11 in Generic helpers, step 15 of 20 in Generics.

← Previous Next →

Unique by key in other languages