Menu
Coddy logo textTech

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 icon

Challenge

Easy

Create 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)
}
quiz iconTest yourself

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

All lessons in Logic & Flow