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)
- Use a Set to track which keys you have already seen.
- Use Array.prototype.filter to build the result array.
- For each element, compute the key and check if it is in the Set.
- Add new keys to the Set and include the element; skip duplicates.
Topics
- Utility Functions
Asked at
Amazon · Microsoft · Uber
