Overview

Sets are similar to arrays in that they are enumerable but sets only hold unique values. The great thing about sets is you don't need a key or index to delete vaules because each value will be unique.

Code

Example : Creating a Set

//ES6 Maps and Sets - Creating and adding items;

// Set stores unique values
// each value can only appear once
let set = new Set([1, 1, 1]);

for (element of set) {
  console.log(element);
}

1
2
3
4
5
6
7
8
9
10

Example : Adding to a Set

//ES6 Maps and Sets - Adding items to a set;


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

set.add(2);
set.add(2); // wont be added because set's values must be unique


for (element of set) {
  console.log(element);
}

1
2
3
4
5
6
7
8
9
10
11
12
13

Example : Removing from a set

//ES6 Maps and Sets - Deleting values from a set;


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

set.add(2);

set.delete(1); // Delete from the set by key

set.clear(); //Removes all values from the set


for (element of set) {
  console.log(element);
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

Example : Checking for something in a set

//ES6 Maps and Sets - Checking for values in a set;

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

set.add(2);

console.log(set.has(1)); //returns boolean if set contains x

for (element of set) {
  console.log(element);
}

1
2
3
4
5
6
7
8
9
10
11
12

Loop through sets

//ES6 Maps and Sets - Looping through sets;


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

set.add("aseq");


//Looping through sets with entries(), returns arrays of key/value pairs
for (element of set.entries()) {
  console.log(element);
}



//Looping through sets with values(), returns values in the set
for (element of set.values()) {
  console.log(element);
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Last Updated: 8/13/2019, 6:55:26 PM