Set in JavaScript can easily remove duplicates from an array. A Set is a collection of values where each value must be unique. When you convert an array to a set, all duplicate values are automatically removed.
Here’s an example:
Example in JavaScript:
// Original array with duplicates const arrayWithDuplicates = [1, 2, 3, 4, 5, 1, 2, 6, 3]; // Convert the array to a Set to remove duplicates, then convert it back to an array const arrayWithoutDuplicates = [...new Set(arrayWithDuplicates)]; console.log(arrayWithoutDuplicates);
Output:
[1, 2, 3, 4, 5, 6]
Explanation:
- We created a
Setfrom the arrayarrayWithDuplicates. This automatically removes any duplicate elements. - Using the spread syntax (
...), we converted theSetback into an array.