There are many ways to remove duplicates from array in JavaScript but today I will use indexOf and filter methods!
The indexOf() method returns the index of the first occurrence of an element in an array. For example:
let chars = ['A', 'B', 'A', 'C', 'B'];
chars.indexOf('B');
Output: 1
To remove the duplicates, you use the filter() method to include only elements whose indexes match their indexOf values:
const arr = ['A', 'B', 'A', 'C', 'B'];
const uniqueArr = arr.filter((c, index) => {
return arr.indexOf(c) === index;
});
console.log(uniqueArr);
Output: [ 'A', 'B', 'C' ]
To find the duplicate values, you just need to reverse the condition:
const arr = ['A', 'B', 'A', 'C', 'B'];
const uniqueArr = arr.filter((c, index) => {
return arr.indexOf(c) !== index;
});
console.log(uniqueArr);
Output: [ 'A', 'B' ]
Top comments (2)
Thanks for your post! It's an interesting approach. Yet, I think there's an easier way to remove all duplicates. Take a look at tip #2:
14 Awesome JavaScript Array Tips You Should Know About
Kai ・ Dec 9 '20 ・ 9 min read
Yes, Set is also used to get a unique array.
Thanks, great post