Remove Duplicates Using Set in JavaScript: Simple Guide
You can remove duplicates from an array in JavaScript by converting it to a
Set, which only stores unique values, and then converting it back to an array using the spread operator [...new Set(array)]. This method is simple and efficient for removing duplicates.Syntax
The basic syntax to remove duplicates using Set is:
new Set(array): Creates a set from the array, automatically removing duplicates.[...set]: Uses the spread operator to convert the set back into an array.
javascript
const uniqueArray = [...new Set(array)];
Example
This example shows how to remove duplicates from an array of numbers using Set and the spread operator.
javascript
const numbers = [1, 2, 2, 3, 4, 4, 5]; const uniqueNumbers = [...new Set(numbers)]; console.log(uniqueNumbers);
Output
[1, 2, 3, 4, 5]
Common Pitfalls
One common mistake is trying to remove duplicates without converting the Set back to an array, which leaves you with a Set object instead of an array.
Another pitfall is using methods like filter or loops unnecessarily when Set provides a simpler solution.
javascript
const numbers = [1, 2, 2, 3]; const wrong = new Set(numbers); console.log(wrong); // Outputs a Set, not an array const right = [...new Set(numbers)]; console.log(right); // Outputs an array with unique values
Output
Set(3) { 1, 2, 3 }
[1, 2, 3]
Quick Reference
Remember these tips when removing duplicates with Set:
- Use
new Set(array)to create a unique collection. - Convert back to array with
[...set]for array methods. - This works for primitive values like numbers and strings.
- For objects, duplicates are based on reference, not content.
Key Takeaways
Use
new Set(array) to remove duplicates efficiently.Convert the Set back to an array with the spread operator
[...set].This method works best for arrays of primitive values like numbers and strings.
Remember that Sets compare objects by reference, so object duplicates may not be removed.
Avoid unnecessary loops or filters when
Set provides a simpler solution.