Sets

All about Sets in JavaScript


Set is a built-in object collection of unique values, where duplicates are not allowed.

A Set can store any type of value, including objects, and provides methods to add, remove, and check if a value exists in the set.

const mySet = new Set()

add()

mySet.add(1)
mySet.add("two")
mySet.add(true)

delete()

mySet.delete(2)
// => {1, "two"}

size

mySet.size
// => 2

has()

mySet.has(1) // => true
mySet.has("three") // => false

forEach()

mySet.forEach((value) => {
  console.log(value)
})
// 1
// "two"

for of

for (let value of mySet) {
  console.log(value)
}
// 1
// "two"

clear()

mySet.clear() // => {}

Array to Set

Convert an Array to Set.

let arrayToSet = new Set(arr)