Chapter 10 Cheatsheet: Sets
This cheatsheet summarizes the mechanics of the JavaScript Set object covered in Chapter 10.
Core Operations
A Set is a collection of strictly unique values. It is highly optimized for verifying existence.
const mySet = new Set([1, 2, 2, 3]); // Initializes as {1, 2, 3}
mySet.add(4); // Adds a value
mySet.delete(2); // Removes a value
Array De-duplication
The most common use case for a Set in standard web development is rapidly removing duplicate values from an Array.
const rawArray = ["apple", "apple", "banana"];
// 1. Pass the array into a new Set
// 2. Spread the Set back into array brackets
const uniqueArray = [...new Set(rawArray)];
console.log(uniqueArray); // ["apple", "banana"]
Set Composition Methods
Modern JavaScript supports native Set theory operations to compare two distinct Sets.
.intersection()
Returns elements present in BOTH sets.
const setA = new Set([1, 2]);
const setB = new Set([2, 3]);
setA.intersection(setB); // Set { 2 }
.difference()
Returns elements present in the first set, but NOT the second.
const setA = new Set([1, 2]);
const setB = new Set([2, 3]);
setA.difference(setB); // Set { 1 }
.union()
Returns all elements from EITHER set.
const setA = new Set([1, 2]);
const setB = new Set([2, 3]);
setA.union(setB); // Set { 1, 2, 3 }