What is the Set object and how does it work?

The Set object is an ES6 feature that lets you store unique values, primitives or object references. A value in a Set can only occur once. It checks if a value exists in the set object using the SameValueZero algorithm.

We can make Set instance using Set constructor and we can optionally pass an Iterable as the initial value.


const set1 = new Set();
const set2 = new Set(["a","b","c","d","d","e"]);

We can add a new value into the Set instance using the add method and since the add returns the Set object we can chain add calls. If a value already exists in Set object it will not be added again.


set2.add("f");
set2.add("g").add("h").add("i").add("j").add("k").add("k");
// the last "k" will not be added to the set object because it already exists

We can remove a value from the Set instance using the delete method, this method returns a boolean indicating true if a value exists in the Set object and false indicating that value does not exist.


set2.delete("k") // returns true because "k" exists in the set object
set2.delete("z") // returns false because "z" does not exists in the set object

We can check if a specific value exists in the Set instance using the has method.


set2.has("a") // returns true because "a" exists in the set object
set2.has("z") // returns false because "z" does not exists in the set object

We can get the length of the Set instance using the size property.


set2.size // returns 10

We can delete or remove all the elements in the Set instance using the clear.


set2.clear(); // clears the set data

We can use the Set object for removing duplicate elements in an array.


const numbers = [1, 2, 3, 4, 5, 6, 6, 7, 8, 8, 5];
const uniqueNums = [...new Set(numbers)]; // has a value of [1,2,3,4,5,6,7,8]