3 ways to remove duplicates in an Array in Javascript
Lenin Felix
Posted on September 7, 2021
Let's check, many times (or few) arises the need to remove duplicate elements given in an array, I don't know... it can be because you have to print a list from the super, remove a student that duplicated his record in a form, infinity of things, so let's see some ways to do this:
1) Use Set
Using Set(), an instance of unique values will be created, implicitly using this instance will delete the duplicates.
So we can make use of this instance and from there we will have to convert that instance into a new array, and that would be it:
let chars = ['A', 'B', 'A', 'C', 'B'];
let uniqueChars = [...new Set(chars)];
console.log(uniqueChars);
Output:
['A', 'B', 'C']
2) Using the indexOf() and filter() methods
The indexOf() method returns the index of the first occurrence of the element in the array:
let chars = ['A', 'B', 'A', 'C', 'B'];
chars.indexOf('B');
Output:
1
The duplicate element is the element whose index is different from its indexOf() value:
let chars = ['A', 'B', 'A', 'C', 'B'];
chars.forEach((element, index) => {
console.log(`${element} - ${index} - ${chars.indexOf(element)}`);
});
Output:
A - 0 - 0
B - 1 - 1
A - 2 - 0
C - 3 - 3
B - 4 - 1
To eliminate duplicates, the filter() method is used to include only the elements whose indexes match their indexOf values, since we know that the filer method returns a new array based on the operations performed on it:
let chars = ['A', 'B', 'A', 'C', 'B'];
let uniqueChars = chars.filter((element, index) => {
return chars.indexOf(element) === index;
});
console.log(uniqueChars);
Output:
['A', 'B', 'C']
And if by chance we need the duplicates, we can modify our function a little, just by changing our rule:
let chars = ['A', 'B', 'A', 'C', 'B'];
let dupChars = chars.filter((element, index) => {
return chars.indexOf(element) !== index;
});
console.log(dupChars);
Output:
['A', 'B']
3) Using the includes() and forEach() methods
The include() function returns true if an element is in an array or false if it is not.
The following example iterates over the elements of an array and adds to a new array only the elements that are not already there:
let chars = ['A', 'B', 'A', 'C', 'B'];
let uniqueChars = [];
chars.forEach((element) => {
if (!uniqueChars.includes(element)) {
uniqueChars.push(element);
}
});
console.log(uniqueChars);
Output:
['A', 'B', 'C']
Basically, we have options to solve this type of problem, so don't get stuck anymore and you can use whichever one appeals to you.
Posted on September 7, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.