Skip to content

uniqueBy

Removes duplicate items from an array, using a derived key instead of value equality. Unlike unique, which compares values directly, uniqueBy lets two different objects be considered duplicates if keyFn derives the same key for both. null and undefined are treated as empty arrays and return [].

Available since v3.0.8

import { uniqueBy } from '@helpers4/array';
// or, from the all-in-one package (same code, one install):
import { uniqueBy } from 'helpers4/array';
uniqueBy<T, K>(array: readonly T[] | null | undefined, keyFn: function, options: UniqueByOptions): T[]
ParameterTypeDescription
arrayreadonly T[] | null | undefinedThe array to remove duplicates from
keyFnfunctionDerives the dedup key for an item
optionsUniqueByOptionsOptions

T[] — New array with one item per distinct key, in first-occurrence order

Deduplicate by a derived key, keeping the first occurrence

Section titled “Deduplicate by a derived key, keeping the first occurrence”

Two different objects are considered duplicates when keyFn derives the same key for both.

uniqueBy(
  [{ id: 1, v: 'a' }, { id: 2, v: 'b' }, { id: 1, v: 'c' }],
  (item) => item.id,
)
// => [{ id: 1, v: 'a' }, { id: 2, v: 'b' }]

Pass { keep: “last” } to keep the last item seen for each key, instead of the first.

uniqueBy(
  [{ id: 1, v: 'a' }, { id: 2, v: 'b' }, { id: 1, v: 'c' }],
  (item) => item.id,
  { keep: 'last' },
)
// => [{ id: 1, v: 'c' }, { id: 2, v: 'b' }]

Options for uniqueBy.

interface UniqueByOptions {
  keep?: "first" | "last";
}

View source on GitHub