Menu
Coddy logo textTech

Math - Union Of Sets

Part of the Logic & Flow section of Coddy's JavaScript journey — lesson 36 of 65.

The union of two sets A and B is a new set that contains all elements from both A and B, without duplicates.

Here's how to create a union of two sets:

function union(setA, setB) {
  return new Set([...setA, ...setB]);
}

const setA = new Set([1, 2, 3]);
const setB = new Set([3, 4, 5]);
const unionSet = union(setA, setB);

console.log(unionSet); // Set(5) { 1, 2, 3, 4, 5 }

In this example, the spread operator (...) is used to convert each Set into an array, which are then combined into a new array. This new array is used to create a new Set, automatically removing any duplicates.

challenge icon

Challenge

Easy

Create a function called setUnion that takes two arrays as parameters. The function should convert that arrays to sets and create a new Set that is the union of the two input Sets. Finally convert the set to an array and return it.

Do not use the spread operator in your solution.

Cheat sheet

The union of two sets creates a new set containing all elements from both sets, without duplicates.

Create a union using the spread operator:

function union(setA, setB) {
  return new Set([...setA, ...setB]);
}

const setA = new Set([1, 2, 3]);
const setB = new Set([3, 4, 5]);
const unionSet = union(setA, setB);

console.log(unionSet); // Set(5) { 1, 2, 3, 4, 5 }

The spread operator (...) converts each Set into an array, which are then combined into a new array to create a new Set, automatically removing duplicates.

Try it yourself

function setUnion(arr1, arr2) {
     const set1 = new Set(arr1)
     const set2 = new Set(arr2)
     // Write your code here
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow