JavaScript data type Set

The Set object holds values of any type. The values can be primitive values or object references. Each value must be unique.

This object is great for when you would use an array but want to make sure that every element is unique. If a duplicate value tries to be added it will be ignored.

Initialize the Set

A Set is initialized by using the new keyword. If nothing is specified (or is null) the value of the Set will empty. Values can be added using the add method as shown below.

let rebels = new Set();
rebels.add("Luke Skywalker");
rebels.add("Han Solo");
rebels.add("Gial Ackber");
rebels.add("Jan Dodonna");

The add method returns the Set which means the the add can be chained, as shown below.

let ships = new Set()
    .add("Death Star")
    .add("Ebon Hawk")
    .add("Tantive IV")
    .add("Millennium Falcon");

An iterable object such as an array can be passed while initializing the Set object. Each item of the array will be added as a value to the Set.

let droids = new Set(["R2-D2", "C-3PO", "2-1B", "BB-9E"]);

Now here’s an interesting little trick. If you initialize a Set using a string, each character will become a seperate value in the Set.

var title = 'Star Wars';

var lettersInTitle = new Set(title);
console.log(mySet.size);  // 7

Whoa? 7? But there are 9 characters in Star Wars? What happen to the other 2 characters? Well, remember each value must be unique. a and r were used twice. S and s are different because of the case, so the Set that is created is ['S','t','a','r',' ','W','s'].

Converting from Array and Set

As we saw in the above section, you can pass an array while creating a Set object. So

let droids = new Set(["R2-D2", "C-3PO", "2-1B", "BB-9E"]);
let droidsArray = [...droids];

If you don’t recognize the spread operator, please look at the blog post at CodeBurst.

Set Properties

Length properties

The property size returns the length of the Set object.


Set Methods

Has method

The has method will return true if the value is in the Set, if not it will return false.

if (rebels.has("Darth Vader")){
    // This will execute if the string "Darth Vader" is part of the Set.

Delete method

The delete method removes that value from the Set.

ships.delete("Death Star");

Foreach method

The forEach method gives you the ability to pass each value, in turn, to a function. In the example I’m using an arrow function.

rebels.forEach((value) => {

for .. of loop

The for .. of loop will execute the block for each value in the Set. Ok, this isn’t really a method, I just wanted to show another example of looping through a Set.

for (let droid of droids){

Clear Method

The clear method will remove all values from the Set.



Mozilla Documentation for Set