Remove duplicates from an array using indexOf() and filter() methods
nouman shah
Posted on January 1, 2021
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' ]
💖 💪 🙅 🚩
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
javascript Mastering Advanced Error Handling in Express.js for Robust Node.js Applications
November 29, 2024