Member-only story
Working with unique values is common in programming. You may need to remove duplicates from an array, check if a value already exists, or operate on a collection of unique items.
JavaScript has a built-in Set object that handles unique values elegantly, yet it often gets overlooked. In this post let’s explore some great ways to put JavaScript Sets to work!
Creating JavaScript Sets
A Set can be initialized from any iterable object, like an array:
const ids = new Set([1, 2, 2, 3]);
// ids = Set(3) {1, 2, 3}
Notice duplicates are automatically removed! We can also create an empty set:
const ids = new Set();
And insert values with .add():
ids.add(4);
// ids = Set(4) {1, 2, 3, 4}
Checking Existence
A key use of sets is quickly checking value existence. The .has() method checks for membership:
ids.has(2);
// true
This provides O(1) lookups versus O(N) searching arrays!