02. Set

Set — коллекция для хранения множества значений, причём каждое значение может встречаться лишь один раз. Set отслеживает дубликаты при помощи того же самого алгоритма, что и Map.

const set = new Set();
set.add("red");
set.size; //  1
set.has("red"); // true
set.delete("red"); // true
set.has("red"); // false

Setting up Set

The Set constructor has zero or one arguments:

  • Zero arguments: an empty Set is created.

  • One argument: the argument needs to be iterable; the iterated items define the elements of the Set.

const empty = new Set();
const colors = new Set(["red", "green", "blue"]);
const set = new Set()
  .add("red")
  .add("green")
  .add("blue");

Set API

Set

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

As you can see, Sets preserve iteration order. That is, elements are always iterated over in the order in which they were inserted. The spread operator (...) works with iterables and thus lets you convert a Set to an Array:

In contrast to Arrays, Sets don’t have the methods map() and filter(). A work-around is to convert them to Arrays and back.

Set operations

Объединение множеств:

Пересечение множеств

Разница множеств:

Last updated

Was this helpful?