Borislav Hadzhiev
Fri Oct 29 2021·2 min read
Photo by Max Vertsanov
To get a union of two Sets, use the spread syntax (...) to unpack the values
of the Sets into an array and pass the result to the Set()
constructor, e.g.
new Set([...set1, ...set2])
. The new Set
will contain the union of the other
two.
const set1 = new Set(['a', 'b', 'c']); const set2 = new Set(['a', 'b', 'd']); const union = new Set([...set1, ...set2]); console.log(union); // 👉️ {'a', 'b', 'c', 'd'}
We used the
spread syntax (...)
to unpack the values from the two Set
objects into an array.
const set1 = new Set(['a', 'b', 'c']); const set2 = new Set(['a', 'b', 'd']); const arr = [...set1, ...set2]; console.log(arr); // 👉️ ['a', 'b', 'c' ,'a', 'b', 'd']
The array stores duplicate values as opposed to a Set
. Once the array is
passed to the Set()
constructor, all of the duplicates are ignored.
The Set() constructor takes an iterable object as a parameter, so an array is perfect.
To get a union of two Sets, pass the first Set
to the Set()
constructor to
create a third Set
. Then use the for...of
loop to iterate over the second
Set
and add each element to the newly created Set
. The new Set
will
contain a union of the other two Sets.
function getUnion(setA, setB) { const union = new Set(setA); for (const element of setB) { union.add(element); } return union; } const set1 = new Set(['a', 'b', 'c']); const set2 = new Set(['a', 'b', 'd']); console.log(getUnion(set1, set2)); // 👉️ {'a', 'b', 'c', 'd'}
We created a reusable function which returns the union of two Sets.
The first step is to create a new Set
from the first Set
.
Then, we used the
for...of
loop to iterate over the second Set
and add its values to the new Set
.