DEV Community

nouman shah
nouman shah

Posted on

5

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

Image of Stellar post

How a Hackathon Win Led to My Startup Getting Funded

In this episode, you'll see:

  • The hackathon wins that sparked the journey.
  • The moment José and Joseph decided to go all-in.
  • Building a working prototype on Stellar.
  • Using the PassKeys feature of Soroban.
  • Getting funded via the Stellar Community Fund.

Watch the video

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay