Algobook
- The developer's handbook
mode-switch
back-button
Buy Me A Coffee
Thu Apr 06 2023

A short tutorial on how to remove duplicates in an Array in Javascript

In this tutorial, we will demonstrate how to remove dulicates from an array in JavaScript. The scenarios when we need to do that, are surprisinly often, at least from my own experience.

Convert to a set

Converting our array to a set and then back to an array is an effective way of solving this issue. Let's have a look how that can be done.

const duplicatedValues = [1, 2, 3, 3, 2, 1]; const mySet = [...new Set(duplicatedValues)]; console.log(mySet); // [1,2,3]

Using filter

We can also use filter to get the job done.

const duplicatedNames = ["John", "Cleo", "John", "Sara", "Sara"]; const uniqueNames = duplicatedNames.filter( (name, idx) => duplicatedNames.findIndex((currentName) => currentName === name) === idx ); console.log(uniqueNames); // [ 'John', 'Cleo', 'Sara' ]

What about objects?

We covered the more easier scenarios. What about when working with objects? Let's have a look:

const cars = [ { name: "Volvo" }, { name: "Tesla" }, { name: "Ford" }, { name: "Volvo" }, ]; const uniqueCars = [...new Set(cars)]; console.log(uniqueCars) [ ({ name: "Volvo" }, { name: "Tesla" }, { name: "Ford" }, { name: "Volvo" }) ];

Wait? Why is it not working? That is because an object is always falsy when doing a comparision ({} is not equal to {}).

Let's solve it!

const cars = [ { name: "Volvo" }, { name: "Tesla" }, { name: "Ford" }, { name: "Volvo" }, ]; const uniqueCars = cars.filter( (car, idx) => cars.findIndex((c) => c.name === car.name) === idx ); console.log(uniqueCars); [{ name: "Volvo" }, { name: "Tesla" }, { name: "Ford" }];

There we go. We need to check for the object property that we know is the duplicate. In this case, the name.

Outro

So, this was a super quick guide on how to remove duplicates. There are many more ways of doing it, but we covered the basics here.

Have a great day and thanks for reading!

signatureThu Apr 06 2023
See all our articles