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
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
APISets 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, Set
s 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:
const set = new Set(["red", "green", "blue"]);
const arr = [...set]; // ['red', 'green', 'blue']
In contrast to Arrays, Sets don’t have the methods map()
and filter()
. A work-around is to convert them to Arrays and back.
// Mapping:
const set = new Set([1, 2, 3]);
set = new Set([...set].map(x => x * 2));
// Resulting Set: {2, 4, 6}
// Filtering:
const set = new Set([1, 2, 3, 4, 5]);
set = new Set([...set].filter(x => x % 2 == 0));
// Resulting Set: {2, 4}
Set operations
Объединение множеств:
const a = new Set([1, 2, 3]);
const b = new Set([4, 3, 2]);
const union = new Set([...a, ...b]);
Пересечение множеств
const a = new Set([1, 2, 3]);
const b = new Set([4, 3, 2]);
const intersection = new Set([...a].filter(x => b.has(x)));
// {2,3}
Разница множеств:
const a = new Set([1, 2, 3]);
const b = new Set([4, 3, 2]);
const difference = new Set([...a].filter(x => !b.has(x)));
Last updated
Was this helpful?