How to automatically remove duplicates from an ES6 array?

In ES6, you can use the Set data structure to automatically remove duplicates from an array. Set is a data structure similar to an array that can store unique values of any type.

You can achieve automatic deduplication of an array by following these steps:

  1. Create a new set called uniqueSet.
  2. Loop through the array and for each item add it to a set called uniqueSet.
  3. Create a unique array by converting a unique set into an array.

The complete code example is as follows:

const array = [1, 2, 3, 4, 4, 5, 5, 6];
const uniqueSet = new Set();
array.forEach(item => uniqueSet.add(item));
const uniqueArray = Array.from(uniqueSet);
console.log(uniqueArray); // 输出:[1, 2, 3, 4, 5, 6]

Furthermore, ES6 also offers a more concise way to automatically remove duplicates from an array, using the spread operator as shown below:

const array = [1, 2, 3, 4, 4, 5, 5, 6];
const uniqueArray = [...new Set(array)];
console.log(uniqueArray); // 输出:[1, 2, 3, 4, 5, 6]

Using the Set data structure can easily achieve automatic deduplication of arrays, but it should be noted that the values stored in the Set are unique, and their data types will not undergo implicit conversion. So if there are values in the array that are both strings and numbers similar, they will still be treated as different values.

广告
Closing in 10 seconds
bannerAds