How to Remove Duplicates from an Array using the Set Datatype

Published on October 23, 2019

Use-Cases of this Tutorial

  • Know how to remove duplicate entries from a Javascript array using the Set data type.

Duplicate elements can be removed from a Javascript array using the Set data type. A Set object can be created from the array, and then the Set can be converted back to an array.

There are many ways of removing duplicate entries from an array, however using the Set data type to do so is the most simplest way — it will consume the least amount of code. Also because Sets are a built-in feature, we can be sure that it will give bug-free results.

Sets are a new data type introduced in Javascript. Like arrays it is also a collection of elements, but a Set can only hold distinct elements. It will not hold duplicate elements.

So to eliminate duplicates from an array we can follow this process :

  • Initialize a Set from the given array.
  • The Set will automatically remove the duplicates.
  • Get the elements of the Set returned as an array.

Initializing Set from an Array

A Set can be initialized with any iterable object — any object that can be looped using a for..of statement. Obviously arrays can be looped through using this.

var arr = [1, 2, 3, 4, 5, 4, 3, 56, 2, 56, 1, 7, 7];

// initialize Set from an array
var set_ob = new Set(arr);

Creating the Set has automatically eliminated all duplicates. However this is a Set data type, we will need as an array data type.

Set to an Array using the Spread Operator

The Spread operator represented by three dots ... expands a given iterable object. A Set is also an iterable object (it can be looped using for..of).

Spread operator gets individual elements from the Set. We can then initialize a new array from these individual elements.

Below are the final codes to remove duplicates from an array :

// given array
var arr = [1, 2, 3, 4, 5, 4, 3, 56, 2, 56, 1, 7, 7];

// new Set
var set_ob = new Set(arr);

// new array using spread operator on Set
var new_arr = [ ...set_ob ];

// [ 1, 2, 3, 4, 5, 56, 7 ]

Useful Resources

Loading Comments