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
EasyCreate 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
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String FundamentalsIterate Over StringsTemplate LiteralsString MethodsRecap - String Weaver4JSON Part 2
Iterate Over JSONNested JSONJSON Optional ChainingShallow And Deep CopyRecap - Bicycle ShopRecap - Solar System10Manage Festival System
Project OverviewAdd Movies & Venues2Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysMatrix Addition & SubstractionJagged Arrays3D Arrays And BeyondCommon 2D Array PatternsRecap - All About Arrays5Sets Part 1
What Is A Set?Iterating Over SetsAdding An ElementRemoving An ElementChecking If An Element ExistsSize And Is EmptyCopy And ClearRecap - Basic Of Sets8Arrays Interesting Topics
Array DestructuringSpread Syntax in ArraysSparse ArraysRecap - Arrays Workshop3JSON Part 1
What is a JSON?Check If Key ExistsObject MethodsThe Spread Operator Part 1The Spread Operator Part 2Remove KeysRecap - JSON Manipulate Keys6Sets Part 2
Math - Union Of SetsMath - Intersection Of SetsMath - Difference Of SetsMath - Symmetric DifferenceSubsets And SuperSetsRecap - Group Friends