DEV Community

avidworks
avidworks

Posted on

A quick way to deduplicate arrays in JavaScript

Need an easy way to deduplicate an array of numbers or strings in Javascript? Use a Set!

Here's how it's done in its simplest form:

const nums = [1,1,1,3,3,5,8,9,9,9,9,9,10]
const uniqueNums = [...new Set(nums)] 
// returns [1,3,5,8,9,10]

const strings = ['JavaScript', 'JavaScript', 'React', 'Node', 'Node', 'HTML', 'CSS']
const uniqueStrings = [...new Set(strings)] 
// returns ['JavaScript', 'React', 'Node', 'HTML', 'CSS']
Enter fullscreen mode Exit fullscreen mode

How does this work? To put it simply, each item in a set must be unique. By spreading the Set into an array, you create a new array with only those unique items.

Some caveats: In this simple form, it will not work with nested arrays or arrays of objects, since they are only duplicates in appearance -- Behind the scenes, they're new copies and thus will not be purged out by using this method. You can get creative to figure out how to do this (reduce would work here!), however it's always better to handle this on the back end!

Learn more about Sets here

Oldest comments (0)