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:

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

or

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

const array = [1, 2, 3, 3, 3, 4];

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

// uniqueArray === [1,2,3,4]

Utility Function to Remove Duplicates with Set Object

We can create a simple utility function to make this reusable:

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

Usage

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