'Add an element to a const set
How would you add an element to an existing Set when defining it? For example, if I have:
const s1 = Set([1,2,3]);
const elem = 4;
const s2 = s1 + elem; // ?
Is using the spread operator (...) the correct way to do this?
s2 = new Set([...s, elem]);
Or is there another/better approach?
Solution 1:[1]
Just use Set#add. Using const here only prevents setting s1 to another value, but does not make the Set immutable.
const s1 = new Set([1,2,3]);
const elem = 4;
s1.add(elem);
console.log([...s1]);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Unmitigated |
