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
Section titled “Import”Signature
Section titled “Signature”Parameters
Section titled “Parameters”| Parameter | Type | Description |
|---|---|---|
array | readonly T[] | null | undefined | The array to remove duplicates from |
keyFn | function | Derives the dedup key for an item |
options | UniqueByOptions | Options |
Returns
Section titled “Returns”T[] — New array with one item per distinct key, in first-occurrence order
Examples
Section titled “Examples”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.
Keep the last occurrence instead
Section titled “Keep the last occurrence instead”Pass { keep: “last” } to keep the last item seen for each key, instead of the first.
Related Types
Section titled “Related Types”UniqueByOptions
Section titled “UniqueByOptions”Options for uniqueBy.
