Q7: Remove Duplicate Values from an Array
Deduplicate elements in an array using an ES6 Set for linear performance, or Array.prototype.filter() with indexOf() for a single-line functional approach.
Array Deduplication Approaches
// Approach 1: ES6 Set (Optimal O(n))
const uniqueSet = (arr) => [...new Set(arr)];
// Approach 2: Array filter (O(n²))
const uniqueFilter = (arr) => arr.filter((item, index) => arr.indexOf(item) === index);
console.log(uniqueSet([1, 2, 2, 3, 4, 4])); // [1, 2, 3, 4]💡 ES6 Set automatically discards duplicate values in linear time, while filter + indexOf scans the array repeatedly.
Key Takeaways
- Set approach provides O(n) time complexity.
- filter + indexOf provides O(n²) time complexity due to internal lookup overhead.
Knowledge Check
Why is the Set approach preferred over filter + indexOf for large arrays?