Three Easy Ways to Remove Duplicate Array Values in JavaScript
Don’t get duped by dupes
There are a multiple ways of removing duplicate values in an array. Before you jump into a recommended method, ask yourself what ES version are you working with?
We’ll go through three strategies to remove duplicate values. Each strategy will use newer conventions, resulting in more efficient code. For the sake of saving space, assume each code snippet uses a variable named items that is an array with some duplicate values.
For Loop with .indexOf()
This first method is battle-tested and guaranteed to work with even the oldest infrastructure.
We’ll begin by defining a new array to hold unique values and then use a for loop to manually check each value with the indexOf() method. When indexOf() returns a -1, we know the value is not yet in our unique array.var unique = [];for(var i=0; i < items.length; i++) {
if(unique.indexOf(items[i]) == -1) {
unique.push(items[i]);
}
}
.filter() with .indexOf()
This second sequence will require ES5, which was released in 2009.
Using .filter(), we avoid predefining an empty array and bypass the for loop. The secret sauce to this strategy is that .indexOf() will return the index of the value when found starting from the left. This means that if the current index does not match the return of .indexOf(), then we found a duplicate.var unique = items.filter(
(item, index) => {
return items.indexOf(item) == index;
}
);
Set() with Spread Operator
This final strategy utilizes features from ES6, released in 2015.
With ES6, JavaScript supports the Set() data structure which by definition only holds unique values. The one downside to using Set() is we are no longer left with an array. We use the spread operator to remedy this, unpacking the set into a newly formed array.const unique = [... new Set(items)];
You will need to decide which implementation to choose, based on the environment you are building for. While the natural response is that “newer is better”, don’t forget to factor in code comfort and how well you will be able to recognize the code if and when you revisit.
Please share your experiences, questions, and feedback below. Follow Code 85 for more plain language programming guides. Thanks for reading!