AniUI Academy

Deduplicate a list by a key function

easyArrays & Objects+150 XPPractice

Merge two pages of API results and you get the same record twice — two different object references holding the same id. A Set is no help, because the objects are not identical references.

Implement uniqueBy(items, keyFn). For each item, call keyFn(item) to get its identity. Return a new array containing only the first item seen for each distinct key, in the order those items appeared in the input. Keys are compared the way a Set compares values, so 1 and "1" are different keys. An empty input returns an empty array. Never modify items.

Arguments

itemsArray
The input list to deduplicate.
keyFn(item) => any
Called with each item to derive its identity for comparison.

Returns

Array — A new array holding the first item seen for each distinct key, in original order.

Examples

uniqueBy(
  [{ id: 1 }, { id: 2 }, { id: 1 }],
  (item) => item.id,
);
// [{ id: 1 }, { id: 2 }]

The second { id: 1 } is dropped — only the first occurrence is kept.

uniqueBy([1, "1", 2], (value) => value);
// [1, "1", 2] — Set-style equality keeps 1 and "1" distinct

What it has to do

  • Keep the first item for each distinct key and drop later ones.
  • Preserve the original relative order of the items you keep.
  • Compare keys by value the way Set does, so 1 and "1" are distinct.
  • Return [] for an empty input array.
  • Do not mutate the input array.
Asked atShopifyAtlassian

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
5 tests · +150 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.