Lesson 1 of 8
Removing duplicates
- 11 min
- 5 checks
- 3 hints
- Go to task
Goal
A one-line Set solution, then the harder case
Explanation
Removing duplicates from simple values is easy: [...new Set(arr)] is all it takes, because a Set won't hold the same value twice, and it keeps each value in the order it first appeared.
Objects are a different story. Two objects with the same contents are still two different references, so a Set sees them as different. The fix is to pick a key that identifies each object and build a Map keyed by it.
A Map keeps insertion order too, so the result comes out in the same order as the original items.
Your task
Write unique(arr) for simple values and uniqueBy(arr, key) for objects.
Checks
5 checks- unique removes duplicates
- unique keeps the order of first appearance
- An empty array returns an empty array
- uniqueBy removes duplicate objects by key
- uniqueBy keeps the first occurrence, not the last