Remove Duplicate Items In Arrays with the Javascript Set Object
March 22, 2020
Javascript has many ways to remove duplicate items from an array. But, for practical purposes, the Set object is the shortest and easiest to understand.
Using the Javascript Set object to remove duplicates
The Set object only allows you to store unique values and will, therefore, remove any duplicated values automatically. Assuming you have an array named array, you can remove duplicates with the Set object in two ways:
1.const uniqueArray = [...new Set(array)];
or
1.const uniqueArray = Array.from(new Set(array));
This is a two-step process:
- Convert our array to a Set object
- Convert the newly created Set object back to an array
We create a new Set object using the new keyword: new Set(array). We create an array in Javascript using either [...values] or Array.from(values).
Usage
1.const array = [1, 2, 3, 3, 3, 4];2.3.const uniqueArray = [...new Set(array)];4.5.// uniqueArray === [1,2,3,4]
Utility Function to Remove Duplicates with Set Object
We can create a simple utility function to make this reusable:
1.const removeDuplicates = arr => [...new Set(arr)];
Usage
1.removeDuplicates([1, 2, 3, 3, 3, 4]); // [1,2,3,4]
More JavaScript Snippets
Popular Articles
I Can't Believe It's Not CSS: Styling Websites with SQL
Style websites using SQL instead of CSS. Database migrations for your styles. Because CSS is the wrong kind of declarative.

How I Built an Oreo Generator with 1.1 Sextillion Combinations
Building a web app that generates 1,140,145,285,551,550,231,122 possible Oreo flavor combinations using NestJS and TypeScript.

AI Model Names Are The Worst (tier list)
A comprehensive ranking of every major AI model name, from the elegant to the unhinged. Because apparently naming things is the hardest problem in AI.