Open In App

How to get the union of two sets in JavaScript ?

Last Updated : 01 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

A union set is the combination of two elements. In mathematical terms, the union of two sets is shown by A ∪ B. It means all the elements in set A and set B should occur in a single array. In JavaScript, a union set means adding one set element to the other set. Set automatically take care of the uniqueness of elements.

Below are the approaches through which we get the union of two sets in JavaScript:

  • Using spread Operator
  • Using add() Method

Approach 1: Using Spread Operator

Spread operator allows an iterable to expand in places where 0+ arguments are expected. It is mostly used in the variable array where there is more than 1 value is expected. It allows us the privilege to obtain a list of parameters from an array.

Example: In this example, we will get the union of the two sets using the javascript spread operator.

Javascript




// One set
const num1 = new Set([1, 2, 3]);
// Another set
const num2 = new Set([4 , 2, 5]);
 
const union = new Set([...num1, ...num2]);
console.log(union);


Output

Set(5) { 1, 2, 3, 4, 5 }

Approach 2: Using add() Method

It is used to append an element with a specified value in a set. It modifies the existing set by appending the new element but does not return a new set.

Example: In this example, we will use add() to union the sets.

Javascript




function showUnion(sA, sB) {
    const union = new Set(sA);
    for (const num of sB) {
        union.add(num);
    }
    return union;
}
const s1 = new Set(['1', '6', '8']);
const s2 = new Set(['2', '3', '4']);
console.log(showUnion(s1, s2));


Output

Set(6) { '1', '6', '8', '2', '3', '4' }


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads