Deduplicate a list by a key function
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.
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
Setdoes, so1and"1"are distinct. - Return
[]for an empty input array. - Do not mutate the input array.
Your workspace
Ready to check it?
5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.
AI Crack & Solution Assist
Stuck? Get instant AI hints or break down the optimal solution.
Stuck? The javascript course covers everything this challenge needs.