Javascript - Collection Set

Introduction

Set objects are collections of unique values and duplicate values are ignored.

Sets values can be primitive types or object references.

Example

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

mySet.size; // 3 

mySet.has(1); // true 

mySet.add('strings'); 
mySet.delete('strings'); // true 
mySet.has('strings'); // false 

mySet.add({ a: 1, b:2 }); 

mySet.size; // 4 
mySet.clear(); // Clears the set 
mySet.size; // 0 

NaN equals NaN when it comes to Set.

You can iterate over a set by insertion order using either the forEach method or the for...of loop:

mySet = new Set([1, 1, 2, 2, 3, 3, { a: 1, b:2 }]); 

mySet.forEach((item) => { 
    console.log(item); 
}); 

// 1 
// 2 
// 3 
// Object { a: 1, b: 2 } 

for (let value of mySet) { 
    console.log(value); 
} 

// 1 
// 2 
// 3 
// Object { a: 1, b: 2 }