DEV Community

nouman shah
nouman shah

Posted on

Remove duplicates from an array using indexOf() and filter() methods

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'); 
Enter fullscreen mode Exit fullscreen mode
Output: 1
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode
Output: [ 'A', 'B', 'C' ]
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode
Output: [ 'A', 'B' ]
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
kais_blog profile image
Kai

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:

Collapse
 
nomishah profile image
nouman shah

Yes, Set is also used to get a unique array.
Thanks, great post