A quick way to deduplicate arrays in JavaScript
avidworks
Posted on March 21, 2022
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']
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!
Posted on March 21, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.