Last updated: Mar 3, 2024
Reading timeยท2 min
To merge Set
objects:
Set
objects
into an array.Set()
constructor.Set
will contain all of the elements from the supplied Set
objects.const set1 = new Set(['bobby', 'hadz']); const set2 = new Set(['com']); const set3 = new Set([...set1, ...set2]); console.log(set3); // ๐๏ธ Set(3) { 'bobby', 'hadz', 'com' }
We used the
spread syntax (...) to
unpack the elements of 2 Set
objects into an array.
const set1 = new Set(['bobby', 'hadz']); const set2 = new Set(['com']); console.log([...set1, ...set2]); // ๐๏ธ [ 'bobby', 'hadz', 'com' ]
The last step is to pass the array to the Set() constructor.
With the values in place, the new Set
looks as follows.
const set3 = new Set(['bobby', 'hadz', 'com']); // ๐๏ธ Set(3) { 'bobby', 'hadz', 'com' } console.log(set3);
This process could be repeated with as many Set
objects as necessary.
const set1 = new Set(['one']); const set2 = new Set(['two']); const set3 = new Set(['three']); const set4 = new Set([...set1, ...set2, ...set3]); console.log(set4); // ๐๏ธ {'one', 'two', 'three'}
Methods like forEach()
iterate over the Set
object in element insertion
order.
If you need to change the insertion order, simply switch the order in which you unpack the values when using the spread syntax.
const set1 = new Set(['one']); const set2 = new Set(['two']); const set3 = new Set(['three']); const set4 = new Set([...set2, ...set1, ...set3]); // ๐๏ธ Set(3) { 'two', 'one', 'three' } console.log(set4);
Notice that the elements got added to the new Set
in the same order in which
we unpacked the Set
objects.
Set
objects using a for...of
loopYou can also use a nested for...of
loop to merge Set
objects.
function mergeSetObjects(...sets) { const set = new Set(); for (const s of sets) { for (const element of s) { set.add(element); } } return set; } const set1 = new Set(['bobby', 'hadz']); const set2 = new Set(['com']); const set3 = mergeSetObjects(set1, set2); console.log(set3); // ๐๏ธ Set(3) { 'bobby', 'hadz', 'com' }
The for...of statement is
used to loop over iterable objects like arrays, strings, Map
, Set
and
NodeList
objects and generators
.
The function takes one or more Set
objects as parameters and uses a for...of
loop to iterate over the collection of Set
objects.
The outer for...loop
iterates over the Set
objects and the inner for...of
loop iterates over each Set
object.
On each iteration, we use the Set.add
method to add the current element to the
new Set
.
The Set.add method inserts a new element
with the supplied value into a Set
object, if the value is not already in the
Set
.
You can learn more about the related topics by checking out the following tutorials: