Handling array duplicates can be tricky. There are multiple ways to remove duplicates from an array, we are going to take a look of Set constructor and a couple of implementatios of indexOf(), filter(), and forEach() methods.

Handling array duplicates can be tricky. There are multiple ways to remove duplicates from an array, we are going to take a look of Set constructor and a couple of implementatios of indexOf(), filter(), and forEach() methods.


Set Constructor

The simplest approach is to use the Set constructor which lets you store unique values of any type, whether primitive values or object references. In other words, Set will automatically remove duplicates for us. The Set constructor get only one argument that is the iterable object wich elements will be added to the new Set. After that we have the unique values and we will spread this values into a new array.

const arrayWithDuplicatesValues = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4];

const arrayWithUniqueValues = [...new Set(arrayWithDuplicatesValues)];

console.log(arrayWithUniqueValues);
// expected output: [1, 2, 3, 4]

for more info about Set take a look at MDN


Filter & IndexOf methods

Another option is to use filter() and indexOf() methods

const arrayWithDuplicatesValues = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4];

const arrayWithUniqueValues = arrayWithDuplicatesValues.filter((value, index) =>
    arrayWithDuplicatesValues.indexOf(value) === index
);

console.log(arrayWithUniqueValues);
// expected output: [1, 2, 3, 4]

for more info about filter or indexOf


Foreach method

The last option is use forEach() to iterate over the array and create an object with keys as the unique values, but keep in mind that the Object.keys() will return an array of strings.

const arrayWithDuplicatesValues = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4];

let unique = {};

arrayWithDuplicatesValues.forEach((value) => {
    if (!unique[value]) {
      unique[value] = true;
    }
});

const arrayWithUniqueValues = Object.keys(unique);

console.log(arrayWithUniqueValues);
// expected output: ["1", "2", "3", "4"]