How to Remove Duplicates from an Array in JavaScript
Sometimes an array needs to only have unique values. In JavaScript, there are multiple ways to approach removing duplicate values from an array and making each element unique, which we will explore in this tutorial.
Using Set()
Set()
is a native JavaScript method that is used to store unique values in an object. Therefore, we can feed it an array containing duplicate values and get an object back with unique values. Let's try it out.
var fruit = ['apples', 'apples', 'oranges', 'strawberries'];
var unqiue = new Set(fruit);
console.log(unqiue);
{"apples", "oranges", "strawberries"}
Now we have an object of unique values we can create a new array from it using the spread operator (...
).
var unqiue_array = [...unqiue];
console.log(unqiue_array);
["apples", "oranges", "strawberries"]
Using the Array Filter Method
We can use the array filter()
method and indexOf()
to return values that only have a unique index value.
var fruit = ['apples', 'apples', 'oranges', 'strawberries'];
var unqiue_array = fruit.filter(function(item, index) {
return fruit.indexOf(item) == index;
});
console.log(unqiue_array);
filter()
creates a new array by looping through the old one. On each iteration we are calling a function containing two arguments. The first (item) is the value of the element and the second is its index.
Inside the function, we are using indexOf()
to look for the first index containing a particular value and only returning that if it matches the current index.
On the second filter()
iteration, indexOf()
would find apples
at index 0, therefore the duplicate apples
at index 1 would not be returned as indexOf()
does not match the current index.
Conclusion
You now know two different ways to remove duplicates from an array in JavaScript. The filter()
method takes a moment of thought to see what is happening, though breaking it down into what each part does will make it easier to understand.