In JavaScript, you can find the union of two sets using the Set data structure and the spread operator or the forEach loop.
In this example,
set1
and set2
....
) to merge set2
into set1
.let set1 = new Set([1, 2, 3]);
let set2 = new Set([3, 4, 5]);
set1 = new Set([...set1, ...set2]);
console.log('Union of set1 and set2:', set1);
Union of set1 and set2: Set { 1, 2, 3, 4, 5 }
In this example,
set1
and set2
.set2
using the forEach loop and add each element to set1
.let set1 = new Set([1, 2, 3]);
let set2 = new Set([3, 4, 5]);
set2.forEach(element => {
set1.add(element);
});
console.log('Union of set1 and set2:', set1);
Union of set1 and set2: Set { 1, 2, 3, 4, 5 }
In this tutorial, we learned How to find Union of Two Sets in JavaScript language with well detailed examples.