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

nomishah

nouman shah

Posted on January 1, 2021

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
💖 💪 🙅 🚩
nomishah
nouman shah

Posted on January 1, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related