Remove Duplicate Items In Arrays with the Javascript Set Object

March 22, 2020

javascript

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:

js
1.const uniqueArray = [...new Set(array)];

or

js
1.const uniqueArray = Array.from(new Set(array));

This is a two-step process:

  1. Convert our array to a Set object
  2. 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

js
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:

js
1.const removeDuplicates = arr => [...new Set(arr)];

Usage

js
1.removeDuplicates([1, 2, 3, 3, 3, 4]); // [1,2,3,4]