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.
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" distinctWhat 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.
Stuck? The javascript course covers everything this challenge needs.
- 1.removes items sharing a key
- 2.keeps the first occurrence, not the last
- 3.treats 1 and "1" as different keys
- 4.returns an empty array for empty input
- 5.does not mutate the input
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.