HomepageExploring JavaScript (ES2024 Edition)
You can support this book: buy it or donate
(Ad, please don’t block.)

37 Sets (Set) [ES6]

Before ES6, JavaScript didn’t have a data structure for sets. Instead, two workarounds were used:

Since ES6, JavaScript has the data structure Set, which can contain arbitrary values and performs membership checks quickly.

37.1 Using Sets

37.1.1 Creating Sets

There are three common ways of creating Sets.

First, you can use the constructor without any parameters to create an empty Set:

const emptySet = new Set();
assert.equal(emptySet.size, 0);

Second, you can pass an iterable (e.g., an Array) to the constructor. The iterated values become elements of the new Set:

const set = new Set(['red', 'green', 'blue']);

Third, the .add() method adds elements to a Set and is chainable:

const set = new Set()
.add('red')
.add('green')
.add('blue');

37.1.2 Adding, removing, checking membership

.add() adds an element to a Set.

const set = new Set();
set.add('red');

.has() checks if an element is a member of a Set.

assert.equal(set.has('red'), true);

.delete() removes an element from a Set.

assert.equal(set.delete('red'), true); // there was a deletion
assert.equal(set.has('red'), false);

37.1.3 Determining the size of a Set and clearing it

.size contains the number of elements in a Set.

const set = new Set()
  .add('foo')
  .add('bar');
assert.equal(set.size, 2)

.clear() removes all elements of a Set.

set.clear();
assert.equal(set.size, 0)

37.1.4 Iterating over Sets

Sets are iterable and the for-of loop works as you’d expect:

const set = new Set(['red', 'green', 'blue']);
for (const x of set) {
  console.log(x);
}

Output:

red
green
blue

As you can see, Sets preserve insertion order. That is, elements are always iterated over in the order in which they were added.

Given that Sets are iterable, you can use Array.from() to convert them to Arrays:

const set = new Set(['red', 'green', 'blue']);
const arr = Array.from(set); // ['red', 'green', 'blue']

37.2 Examples of using Sets

37.2.1 Removing duplicates from an Array

Converting an Array to a Set and back, removes duplicates from the Array:

assert.deepEqual(
  Array.from(new Set([1, 2, 1, 2, 3, 3, 3])),
  [1, 2, 3]);

37.2.2 Creating a set of Unicode characters (code points)

Strings are iterable and can therefore be used as parameters for new Set():

assert.deepEqual(
  new Set('abc'),
  new Set(['a', 'b', 'c']));

37.3 What Set elements are considered equal?

As with Map keys, Set elements are compared similarly to ===, with the exception of NaN being equal to itself.

> const set = new Set([NaN, NaN, NaN]);
> set.size
1
> set.has(NaN)
true

As with ===, two different objects are never considered equal (and there is no way to change that at the moment):

> const set = new Set();

> set.add({});
> set.size
1

> set.add({});
> set.size
2

37.4 Missing Set operations

Sets are missing several common operations. Such an operation can usually be implemented by:

37.4.1 Union (ab)

Computing the union of two Sets a and b means creating a Set that contains the elements of both a and b.

const a = new Set([1,2,3]);
const b = new Set([4,3,2]);
// Use spreading to concatenate two iterables
const union = new Set([...a, ...b]);

assert.deepEqual(Array.from(union), [1, 2, 3, 4]);

37.4.2 Intersection (ab)

Computing the intersection of two Sets a and b means creating a Set that contains those elements of a that are also in b.

const a = new Set([1,2,3]);
const b = new Set([4,3,2]);
const intersection = new Set(
  Array.from(a).filter(x => b.has(x))
);

assert.deepEqual(
  Array.from(intersection), [2, 3]
);

37.4.3 Difference (a \ b)

Computing the difference between two Sets a and b means creating a Set that contains those elements of a that are not in b. This operation is also sometimes called minus (−).

const a = new Set([1,2,3]);
const b = new Set([4,3,2]);
const difference = new Set(
  Array.from(a).filter(x => !b.has(x))
);

assert.deepEqual(
  Array.from(difference), [1]
);

37.4.4 Mapping over Sets

Sets don’t have a method .map(). But we can borrow the one that Arrays have:

const set = new Set([1, 2, 3]);
const mappedSet = new Set(
  Array.from(set).map(x => x * 2)
);

// Convert mappedSet to an Array to check what’s inside it
assert.deepEqual(
  Array.from(mappedSet), [2, 4, 6]
);

37.4.5 Filtering Sets

We can’t directly .filter() Sets, so we need to use the corresponding Array method:

const set = new Set([1, 2, 3, 4, 5]);
const filteredSet = new Set(
  Array.from(set).filter(x => (x % 2) === 0)
);

assert.deepEqual(
  Array.from(filteredSet), [2, 4]
);

37.5 Sets can use operations for iterables

Sets are iterable and therefore can use operations that accept iterables. These are described elsewhere:

37.6 Quick reference: Set

37.6.1 new Set()

37.6.2 Set.prototype.*: single Set elements

37.6.3 Set<T>.prototype: all Set elements

37.6.4 Set<T>.prototype: iterating and looping

37.6.5 Symmetry with Map

The following two methods mainly exist so that Sets and Maps have similar interfaces. Each Set element is handled as if it were a Map entry whose key and value are both the element.

.entries() enables you to convert a Set to a Map:

const set = new Set(['a', 'b', 'c']);
const map = new Map(set.entries());
assert.deepEqual(
  Array.from(map.entries()),
  [['a','a'], ['b','b'], ['c','c']]
);

37.7 FAQ: Sets

37.7.1 Why do Sets have a .size, while Arrays have a .length?

The answer to this question is given in “Why do Maps have a .size, while Arrays have a .length?” (§35.6.4).