A set is a collection of unique values. A set can have elements of any data type.

Create a set object

To create a set object we make use of the new Set() constructor.

let set = new Set();

To add an element to a set, we make use of the add() method.

let set = new Set();

set.add(1);
console.log(set); // {1}

set.add(2);
console.log(set); // {1, 2}

set.add(3);
console.log(set); // {1, 2, 3}

Since the sets contain unique values, we cannot add duplicate values.

let set = new Set();

set.add(1);
console.log(set); // {1}

set.add(2);
console.log(set); // {1, 2}

set.add(2);
console.log(set); // {1, 2}

As you can see, if we try to add 2 the second time, the set simply ignores it.

delete a value from a set

To delete a value from a set object, use the delete() method and specify the value you want to delete.

let set = new Set();

set.add(1);
set.add(2);
set.add(3);
console.log(set); // {1, 2, 3}

set.delete(1);

console.log(set); // {2, 3}

Get the length of the set object

The size property is used to get the length of the set.

let set = new Set();

set.add(1);
set.add(2);
set.add(3);
console.log(set); // {1, 2, 3}

console.log(set.size); // 3

Check if a value exists in a set

To check if a value is present in a set object use the has() method.

let set = new Set();

set.add(1);
set.add(2);
set.add(3);

console.log(set.has(3)); // true

Convert an array to set

You can simply pass the array to the Set constructor to convert an array to a set object.

let set = new Set([1, 2, 3, 4]);

console.log(set); // {1, 2, 3, 4}

Remove duplicate values from an array using Set

To remove duplicate values from an array we can make use of the set object since the set object does not contain duplicate values.

let arr = [1, 2, 3, 4, 4, 5, 5, 6, 6];

let set = new Set(arr);
console.log(set); // {1, 2, 3, 4, 5, 6}

You can covert the set back to an array using the spread operator.

let arr = [1, 2, 3, 4, 4, 5, 5, 6, 6];

let set = new Set(arr);
console.log(set); // {1, 2, 3, 4, 5, 6}

let newArr = [...set];
console.log(newArr); // [1, 2, 3, 4, 5, 6]

Convert string to a set

We can also use a set on strings. The set constructor will convert a string into a set such that each character represents the elements of the set.

let str = "Hello";

let set = new Set(str);
console.log(set); // {'H', 'e', 'l', 'o'}