TypeScript tutorial: Lesson 26 – Set


Starting with ECMAScript 2015, The Set object lets you store unique values of any type, whether primitive values or object references.

Create a Set:

var myMap = new Set()

Or initial by an Array

var mySet2 = new Set(['2',1,{}])

Or initial by other Set

var mySet3 = new Set(mySet)

Or initial by a string

var mySet4 = new Set("hello")
console.log(mySet4) //Set(4) { 'h', 'e', 'l', 'o' }

Adding a value of a Set

Use add(value) method:

var mySet = new Set()
mySet.add('2')
mySet.add(1)
mySet.add({})
mySet.add((a)=>{return a})
console.log(mySet) //Set(4) { '2', 1, {}, [Function (anonymous)] }

Checking a value exists in a Set

Use has(value) method:

console.log(mySet2.has(1)) //true

Delete a value of a Set

Use delete(key) method:

console.log(mySet2.delete(1)) //true

Size of Set

console.log(mySet.size) //4

Iterating Set with forEach()

mySet.forEach(function(value) {
    console.log(value)
})

Result:

2
1
{}
[Function (anonymous)]

Iterating Set with for…of

for(var item of mySet){
    console.log(item)
}

Converting Set to Array

Method 1:

var myArray_1 = Array.from(mySet2)
console.log(myArray_1) //[ '2', {} ]

Method 1:

var myArray_2 = [...mySet2]
console.log(myArray_2) //[ '2', {} ]

Instance methods
Set.prototype.add(value)
Appends value to the Set object. Returns the Set object.
Set.prototype.clear()
Removes all elements from the Set object.
Set.prototype.delete(value)
Removes the element associated to the value and returns the value that Set.prototype.has(value) would have previously returned. Set.prototype.has(value) will return false afterwards.
Set.prototype.has(value)
Returns a boolean asserting whether an element is present with the given value in the Set object or not.

Leave a Reply