Labs ICT
โญ Pro Login

Sets

Creating a Set

A Set stores unique values of any type.

const set = new Set();
set.add(1);
set.add(2);
set.add(2); // duplicate, ignored
set.add("hello");

console.log(set.size); // 3
Try it Yourself โ†’

has and delete

Check values with has, remove with delete, clear all with clear.

const tags = new Set(["js", "html", "css"]);
console.log(tags.has("js"));   // true
console.log(tags.has("php"));  // false

tags.delete("css");
console.log(tags.size); // 2

tags.clear();
console.log(tags.size); // 0

Removing Duplicates from Arrays

Pass an array to the Set constructor to get unique values.

const numbers = [1, 2, 2, 3, 3, 3, 4, 5, 5];
const unique = [...new Set(numbers)];
console.log(unique); // [1, 2, 3, 4, 5]

const word = "hello";
const letters = new Set(word);
console.log([...letters].join("")); // "helo"

Iterating a Set

Sets are iterable and maintain insertion order.

const fruits = new Set(["apple", "banana", "cherry"]);
fruits.forEach(fruit => console.log(fruit));

for (const fruit of fruits) {
  console.log("I like " + fruit);
}

Set Operations (Manual)

JavaScript does not have built-in set operations, but they are easy to implement.

const setA = new Set([1, 2, 3, 4]);
const setB = new Set([3, 4, 5, 6]);

const union = new Set([...setA, ...setB]);
console.log([...union]); // [1, 2, 3, 4, 5, 6]

const intersection = new Set([...setA].filter(x => setB.has(x)));
console.log([...intersection]); // [3, 4]

const difference = new Set([...setA].filter(x => !setB.has(x)));
console.log([...difference]); // [1, 2]

๐Ÿงช Quick Quiz

What makes a Set different from an Array?