Use Set to remove Duplicates from an Array

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 Set from the array arrayWithDuplicates. This automatically removes any duplicate elements.
  • Using the spread syntax (...), we converted the Set back into an array.

Leave a comment

Your email address will not be published. Required fields are marked *