How do you efficiently remove duplicate values from an array?
Short answer
Convert the array to a Set, which only stores unique values, then spread it back into an array. This is O(n) and far simpler than manually filtering with indexOf.
Advertisement
AModel answer
Convert the array to a Set, which only stores unique values, then spread it back into an array. This is O(n) and far simpler than manually filtering with indexOf.
const unique = [...new Set([1,2,2,3,3,3])]; // [1,2,3]Real-world example
Deduplicating a list of tag IDs collected from multiple form submissions.
Likely follow-ups
- How would you dedupe an array of objects by a specific property?
Related topics