DEV Community

Cover image for Javascript Arrays - How to Remove Duplicate Elements
Johnny Simpson
Johnny Simpson

Posted on • Originally published at fjolt.com

Javascript Arrays - How to Remove Duplicate Elements

Javascript arrays can contain duplicates - which is fine most of the time, but can sometimes cause some issues. For example, if an array is supposed to only contain unique user IDs, but is taken from a data source which may contain duplicates:

let userIds = [ '123-123', '123-123', '234-234', '345-345' ]
Enter fullscreen mode Exit fullscreen mode

In these cases, it can seem quite difficult to get only unique values. Is the best way to check every value against every other value in an array? That seems like a lot of work which should be simple. Fortunately, there is an easy way to make a unique array, and that is to use javascript sets.

A set can only contain unique values, so passing your array into a new Set() constructor will produce one set with unique values:

let userIds = [ '123-123', '123-123', '234-234', '345-345' ]
let uniqueUserIds = new Set(userIds)
console.log(uniqueUserIds) // Set(3) {'123-123', '234-234', '345-345'}
Enter fullscreen mode Exit fullscreen mode

While sets have their own methods and these are described in my set guide here, sometimes arrays can be both more familiar and have more useful methods.

To convert your set back to an array, use the Array.from() method:

let userIds = [ '123-123', '123-123', '234-234', '345-345' ]
let uniqueUserIds = new Set(userIds)
let arrayUserIds = Array.from(uniqueUserIds)
console.log(arrayUserIds) // [ '123-123', '234-234', '345-345' ]
Enter fullscreen mode Exit fullscreen mode

Now you have a perfectly unique set of array items - and you won't have to worry about processing times, or inaccuracy.

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (0)

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay