Live streamJoin us for "State of code review 2024" on July 18thRegister today

Sets in TypeScript

Kenny DuMez
Kenny DuMez
Graphite software engineer

This guide will explore the use of sets in TypeScript, including their properties, methods, and how to integrate them into TypeScript projects effectively.

In TypeScript, a Set is a collection of unique values that does not allow duplicate elements. A set is implemented with the Set object, which is part of the ECMAScript 2015 (ES6) specification and fully supported in TypeScript.

To create a set in TypeScript, you simply instantiate a new Set object. You can initialize a set with or without values.

Example:

Terminal
let mySet = new Set<number>() // an empty set of numbers
let stringSet = new Set<string>(['apple', 'banana', 'cherry']) // set initialized with strings

To add items to a set, use the add method. This method appends a new element to a set, only if it is not already present in the collection.

Terminal
mySet.add(1)
mySet.add(2)
mySet.add(1) // this will no-opp, and not add '1' again, as it is a duplicate

To check if an item exists in a set, use the has method.

Terminal
console.log(mySet.has(1)) // true
console.log(mySet.has(3)) // false

has will return true if the element exists in the set, and return false if the element does not exist in the set.

To remove an item, use the delete method.

Terminal
mySet.delete(2) // removes '2' from the set

To remove all items from a set, use the clear method.

Terminal
mySet.clear() // empties the entire set

Sometimes, you might need to convert a set back into an array. You can do this using the spread operator ... or Array.from.

With the spread operator:

Terminal
let arrayFromSet = [...stringSet]
console.log(arrayFromSet) // ['apple', 'banana', 'cherry']

With Array.from:

Terminal
let arrayFromSet2 = Array.from(stringSet)
console.log(arrayFromSet2) // ['apple', 'banana', 'cherry']

Both the spread operator ... and the Array.from() method functionally perform the same, however:

  • Array.from() has additional capabilities: it can accept a map function as a second argument, allowing you to transform elements during the conversion process. For example:
    Terminal
    let arrayFromSet2 = Array.from(stringSet, (value) => value.toUpperCase())
    console.log(arrayFromSet2) // ['APPLE', 'BANANA', 'CHERRY']
  • The spread operator does not directly support transformation during unpacking; any transformation would require a separate operation like map():
    Terminal
    let arrayFromSet = [...stringSet].map((value) => value.toUpperCase())
    console.log(arrayFromSet) // ['APPLE', 'BANANA', 'CHERRY']

You can iterate over the elements of a set using forEach or a for...of loop.

Example with forEach:

Terminal
stringSet.forEach((value) => {
console.log(value)
})

Example with for...of loop:

Terminal
for (let value of stringSet) {
console.log(value)
}

For further reading on the differences between these two loops, see the official TypeScript documentation.

To perform more complex operations like intersections, unions, and differences, you will need to implement helper functions:

Intersection:

Terminal
function intersectSets<T>(setA: Set<T>, setB: Set<T>): Set<T> {
let intersection = new Set<T>()
for (let elem of setB) {
if (setA.has(elem)) {
intersection.add(elem)
}
}
return intersection
}
  • The intersectSets function takes two sets, setA and setB, and returns a new set that includes only the elements that are present in both setA and setB.
  • It iterates through setB, checking if each element is present in setA. If it is, the element is added to the intersection set.

Union:

Terminal
function unionSets<T>(setA: Set<T>, setB: Set<T>): Set<T> {
let union = new Set(setA)
for (let elem of setB) {
union.add(elem)
}
return union
}
  • The unionSets function also takes two sets, setA and setB, and returns a new set containing all elements from both setA and setB.
  • It initializes a new set union with the elements of setA and then adds elements from setB to this set. Since a Set in JavaScript automatically handles duplicates (i.e., it does not add a duplicate element), this function will correctly contain all unique elements from both sets.

Difference:

Terminal
function differenceSets<T>(setA: Set<T>, setB: Set<T>): Set<T> {
let difference = new Set(setA)
for (let elem of setB) {
difference.delete(elem)
}
return difference
}
  • The differenceSets function computes the difference between two sets, setA and setB, returning a new set containing elements that are in setA but not in setB.
  • It initializes a new set difference with the elements of setA and then removes elements found in setB.

For more information on the TypeScript Set object, see the official TypeScript documentation.

Stay unblocked. Ship faster.
Experience the new developer workflow - create, review, and merge code continuously. Get started with one command.
Get started

Give your PR workflow
an upgrade today

Stack easier | Ship smaller | Review quicker

Or install our CLI.
Product Screenshot 1
Product Screenshot 2