Return the unique values of an array
Implement unique(arr) that returns a new array containing each value of arr exactly once, preserving the order of first appearance. unique([1, 2, 2, 3, 1]) returns [1, 2, 3]. The original array must not be mutated.
function unique(arr) {
// your code here
}
Write the implementation.
Pass the array into a Set, which drops duplicates while keeping insertion order, then spread it back: [...new Set(arr)]. Set membership uses SameValueZero, so it dedups primitives correctly (and treats NaN as equal to itself). This is O(n) and never mutates the input.
- ✗Sorting to dedup, which destroys the original order of first appearance
- ✗Assuming a
Setdeduplicates objects by value — it dedups by reference - ✗Using
indexOfinside a loop, turning an O(n) job into O(n²)
- →How does
Setmembership handleNaNdifferently from===? - →How would you dedup an array of objects by a specific property?
Solution
Pass the array into a Set (which drops duplicates) and spread it back into an array.
function unique(arr) {
return [...new Set(arr)];
}
How it works
A Set stores only distinct values and preserves insertion order. Passing arr to the Set constructor discards repeats automatically, and the spread [...] turns the result back into an array. The original array is left untouched.
Set membership uses the SameValueZero algorithm, so primitives compare correctly and NaN is treated as equal to itself (unlike ===). Each element is processed once, giving O(n) time. </content>