Unique By Key Function

EasyUtility Functions10 min4 tests

Implement a uniqueBy function that returns unique elements from an array, determined by a key function.

Requirements

  • Accept an array and a function that extracts the comparison key
  • Keep the first occurrence when duplicates are found
  • Preserve the original order of elements

Example

uniqueBy([{id:1,name:'a'},{id:2,name:'b'},{id:1,name:'c'}], x => x.id);
// [{id:1,name:'a'},{id:2,name:'b'}]
Hints (4)
  1. Use a Set to track which keys you have already seen.
  2. Use Array.prototype.filter to build the result array.
  3. For each element, compute the key and check if it is in the Set.
  4. Add new keys to the Set and include the element; skip duplicates.

Topics

  • Utility Functions

Asked at

Amazon · Microsoft · Uber

Join Us
blur