Unique Elements
Prompt
Write a function that takes an array as input and returns a new array containing only the unique elements (removing all duplicates).
Your solution should maintain the original order of elements, keeping the first occurrence of each element and removing subsequent duplicates.
Program your solution in JavaScript and provide a concise explanation of your approach.
Playground
Consider using a data structure that naturally enforces uniqueness, like a Set. However, remember that you need to maintain the original order of elements.
You can also solve this problem using array methods like filter()
by checking if the current element's index is the first occurrence of that element in the array.
For a manual approach, you could iterate through the array and use an auxiliary data structure to keep track of elements you've already seen.
Solution
Explanation
There are multiple ways to filter unique elements from an array in JavaScript:
Solution 1: Using Set
The most concise solution uses the Set
object, which only stores unique values. By converting the array to a Set
and then back to an array using the spread operator, we get an array of unique elements:
return [...new Set(arr)];
This solution is elegant and efficient with O(n) time complexity. It also correctly handles special values like NaN
, which are considered equal in a Set
.
Solution 2: Using filter()
Another approach is to use the filter()
method combined with indexOf()
:
return arr.filter((item, index) => arr.indexOf(item) === index);
This keeps an element only if its current index matches the first index it appears in the array. This solution has O(n²) time complexity because indexOf()
performs a linear search for each element.
Solution 3: Manual Tracking
For more complex cases or better performance with large arrays, we can manually track elements we've seen:
const result = [];
const seen = {};
for (const item of arr) {
const key = typeof item + JSON.stringify(item);
if (!seen[key]) {
result.push(item);
seen[key] = true;
}
}
return result;
This solution has O(n) time complexity and works well for most cases, though the serialization approach may have limitations with complex objects.
The Set-based solution (Solution 1) is generally preferred for its simplicity and efficiency unless there are specific requirements that necessitate a different approach.
Set and Element Order
It's important to understand that JavaScript's Set
object preserves the insertion order of elements. This wasn't always guaranteed in earlier JavaScript versions, but since ECMAScript 2015 (ES6), the specification requires that Sets maintain insertion order.
This is why the Set-based solution works perfectly for maintaining the original order of unique elements. When we convert an array to a Set and back again:
[...new Set(arr)]
The resulting array will contain unique elements in the same order they first appeared in the original array. This behavior is consistent across all modern browsers and JavaScript engines.
This order preservation is also why the Set solution is superior to using an object-based approach (like creating an object with values as keys and then extracting the keys), as object property iteration order was not guaranteed in older JavaScript versions.