Joe Wayne

I talk about technology, programming and development.

3 methods to remove duplicate items javascript array

There are several ways to remove duplicate items from an array in JavaScript. Below, I will describe three common methods:

1. Using the method filter() and indexOf()

One way to remove duplicate items from an array is to use the method filter()in conjunction with the method indexOf()to filter out non-duplicate elements. The method indexOf()returns the first index at which an element can be found in the array, and if that index is not equal to the current index in the loop filter(), then the element is a duplicate and should not be included in the new array.

const array = [3, 5, 5, 7, 9, 9, 1, 9, 2, 5, 7, 9, 2, 42, 12, 56, 87, 34, 23, 34]; 
const arrayNoDuplicates = array.filter((value, index, self) => {
  return self.indexOf(value) === index;
});
console.log(arrayNoDuplicates);

The above code will print the following output to the console:

[ 3 , 5 , 7 , 9 , 1 , 2 , 42 , 12 , 56 , 87 , 34 , 23 ]

2. Using an object as a filter

Another way to remove duplicate items from an array is by using an object as a filter. In this approach, an object is created to store the unique keys of the array elements, and then these keys are used to create a new array.

const array = [3, 5, 5, 7, 9, 9, 1, 9, 2, 5, 7, 9, 2, 42, 12, 56, 87, 34, 23, 34]; 
const FilterObject = {}; 
const arrayNoDuplicates = array.filter((value) => {
  return FilterObject.hasOwnProperty(value) ? false : (FilterObject[value] = true);
});
console.log(arrayNoDuplicates);

The above code will also print the following output to the console:

[ 3 , 5 , 7 , 9 , 1 , 2 , 42 , 12 , 56 , 87 , 34 , 23 ]  

3. Using the method Set()

Starting with ES6, JavaScript introduced the object Set(), which allows you to store unique values ​​of any type, including elements of an array. With object Set(), we can easily remove duplicate items from an array.

const array = [3, 5, 5, 7, 9, 9, 1, 9, 2, 5, 7, 9, 2, 42, 12, 56, 87, 34, 23, 34]; 
const set = new Set(array); 
const arrayNoDuplicates = Array.from(set);
console.log(arrayNoDuplicates);

The above code will print the following output to the console:

[ 3 , 5 , 7 , 9 , 1 , 2 , 42 , 12 , 56 , 87 , 34 , 23 ]

Deixe um comentário

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *