Set
An object data structure that tracks membership of values. It is like a map, but has no value associated with each key. Its implementation uses a hash table.
Construction
new Set();
Set(0) {}
You may pass an iterable to the constructor.
new Set([1, 2]);
Set(2) {1, 2}
new Set('abcd');
Set(4) {'a', 'b', 'c', 'd'}
Set
const set = new Set();
set.add('hello');
Set(1) {'hello'}
set.add('hello');
Set(1) {'hello'}
Remove
const set = new Set([1, 2, 3]);
set.delete(2);
true
set.delete(2);
false
set;
Set(2) {1, 3}
Check Membership
const set = new Set(['foo']);
set.has('foo');
true
set.has('bar');
false
Member Count
const set = new Set(['a', 'b', 'c', 'd']);
set.size;
4
Iterating
A set is iterable in insertion order.
const set = new Set([1, 2, 3]);
for (const el of set) {
console.log(el);
}
1
2
3
[...set];
[1, 2, 3]
A set also exposes a forEach
function.
const set = new Set(['a', 'b', 'c']);
set.forEach(el => console.log(el));
a
b
c
Examples
new Set([1, 2, 2, 3, 3]);
Set(3) { 1, 2, 3 }