
You may have often come across a requirement to remove duplicate items from a JavaScript array. There are multiple ways to achieve it. Such that,
- Using the forEach loop and manually checking for the duplicate values
- Using the array’s filter method and others
- Using the Set object
Let us say; you have an array as below,
let cities = ['Delhi',
'Delhi',
'Mumbai',
'Chennai',
'Kolkata',
'Bangalore',
'Hyderabad',
'Bangalore'];
You can remove duplicate items, using the filter method as shown below,
cities = cities.filter(
(item, index, inputArray) =>
inputArray.indexOf(item) == index
);
console.log(cities);
The filter method creates a new array with all elements that pass the test implemented. In the above filter method, an arrow function is passed, which contains the test. Inside the arrow function, indexOf() method is used. It returns the index of the first element found or -1 if the element is not found.
Using the filter method is the most popular way of filtering out duplicate items from the array.
However, there is the easiest way to remove duplicate items from a JavaScript array is by using the Set object.
The Set object lets store the unique value of any type, whether primitive values or object reference
Each value on the Set object has to be unique. You can use Set to remove duplicate items from an array as shown below,
let uniqecities = [...new Set(cities)];
console.log(uniqecities);
Since each value in the Set has to be unique, JavaScript checks for value equality. Above, the spread operator is used to convert the Set object to an array.
You can also use Set to find whether an item exists in the array or not
let CitySet = new Set(cities);
console.log(CitySet.has("Delhi")); // true
console.log(CitySet.has("Seattle")); // false
As you see Set makes it very easier to remove duplicate items from an array and for other useful operations on the array.
I hope you find this post useful. Thanks for reading.
Leave a Reply