Math - Intersection Of Sets
Part of the Logic & Flow section of Coddy's JavaScript journey — lesson 37 of 65.
The intersection of two sets A and B is a new set that contains only the elements that are present in both A and B.
To find the intersection of two sets, you can iterate through one set and check if each element exists in the other set:
const set1 = new Set([1, 2, 3]);
const set2 = new Set([2, 3, 4]);
const intersection = new Set();
for (let element of set1) {
if (set2.has(element)) {
intersection.add(element);
}
}Challenge
EasyCreate a function called setIntersection that takes arrays as parameters. The function should convert that arrays to Sets. Create a Set that is the intersection of the two input Sets, convert to an array and return the array. Do not use the spread operator in your solution.
Cheat sheet
The intersection of two sets contains only elements present in both sets.
const set1 = new Set([1, 2, 3]);
const set2 = new Set([2, 3, 4]);
const intersection = new Set();
for (let element of set1) {
if (set2.has(element)) {
intersection.add(element);
}
}Try it yourself
function setIntersection(arr1, arr2) {
const set1 = new Set(arr1)
const set2 = new Set(arr2)
const intersectionSet = new Set();
// Write your code here
return Array.from(intersectionSet)
}
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