JavaScript Program to Merge Two Sets

Given two sets, our task is to Merge Two Sets into a new set so that unique elements will be present in the new set from both sets.

Example:

Input:
set1 = ([1, 2, 3, 4])
set2 = ([3, 4, 5, 6])

Output:
Set(5) { 1, 2, 3,4, 5, 6}

Explanation:
The unique elements present in set are : 1, 2, 3, 4, 5, 6

Below are the approaches to Merge Two Sets using JavaScript:

Table of Content

  • Using forEach() Method
  • Using for…of Loop
  • Using Spread Operator

Using forEach() Method

Create a new Set named mergedSet and initialize it with the elements of set1. Iterate through each element of set2 using the forEach method. Add each element from set2 to the mergedSet using the add method. After merging all elements from set2, return the mergedSet.

Example: The example below shows how to Merge two sets Using the forEach() Method.

JavaScript
function mergeSetFun(set1, set2) {
    const mergSet = new Set(set1);

    // Merge elements from set2
    set2.forEach(element => {
        mergSet.add(element);
    });

    return mergSet;
}

const set1 = new Set([142, 562, 64743, 44]);
const set2 = new Set([573, 142, 6745]);
console.log("Merged set:",
                mergeSetFun(set1, set2));

Output
Merged set: Set(6) { 142, 562, 64743, 44, 573, 6745 }

Time complexity: O(m)

Space complexity: O(n + m)

Using for…of Loop

Create a new Set named mergedSet and initialize it with the elements of set1. Iterate through each element of set2 using a for…of loop. Add each element from set2 to the mergedSet using the add method. After merging all elements from set2, return the mergedSet.

Example: The example below shows how to Merge two sets Using for…of Loop.

JavaScript
function mergSetFun(set1, set2) {
    const mergSet = new Set(set1);

    for (const element of set2) {
        mergSet.add(element);
    }
    return mergSet;
}

const set1 = new Set([10, 20, 30, 40]);
const set2 = new Set([30, 40, 50]);
console.log("Merged set:",
                mergSetFun(set1, set2));

Output
Merged set: Set(5) { 10, 20, 30, 40, 50 }

Time complexity: O(m)

Space complexity: O(n + m)

Using Spread Operator

In this approach, use the spread operator (…) to merge the elements of both sets into a single array. Create a new Set using the array obtained from the spread operator. Return the newly created set containing the merged elements.

Example: The example below shows how to Merge two sets Using the spread operator.

JavaScript
function mergeSetsFun(set1, set2) {
    return new Set([...set1, ...set2]);
}

const set1 = new Set([1545, 2544, 3353, 433]);
const set2 = new Set([3353, 433, 254]);
console.log("Merged set:", 
                    mergeSetsFun(set1, set2));

Output
Merged set: Set(5) { 1545, 2544, 3353, 433, 254 }

Time complexity: O(n + m)

Space complexity: O(n + m)



Contact Us