Menu
Coddy logo textTech

Math - Difference Of Sets

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

The difference of two sets A and B (often written as A - B) is a new set that contains elements that are in A but not in B. This operation is not commutative, meaning A - B is not necessarily the same as B - A.

For example:

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

// A - B: elements in A but not in B
const differenceAB = new Set([...setA].filter(x => !setB.has(x)));
console.log('A - B:', differenceAB); // Set { 1, 2 }

// B - A: elements in B but not in A
const differenceBA = new Set([...setB].filter(x => !setA.has(x)));
console.log('B - A:', differenceBA); // Set { 6, 7 }
challenge icon

Challenge

Easy

Create a function called setDifference that takes two arrays as parameters: arr1 and arr2. The function should convert the arrays to sets. Create a new Set that contains elements that are in set1 but not in set2, convert it an array and return it

Cheat sheet

The difference of two sets A and B (A - B) creates a new set containing elements that are in A but not in B. This operation is not commutative (A - B ≠ B - A).

To find the difference between sets, convert arrays to sets and use set operations to find elements in the first set but not in the second. For example:

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

// A - B: elements in A but not in B
const differenceAB = new Set([...setA].filter(x => !setB.has(x)));
console.log('A - B:', differenceAB); // Set { 1, 2 }

// B - A: elements in B but not in A
const differenceBA = new Set([...setB].filter(x => !setA.has(x)));
console.log('B - A:', differenceBA); // Set { 6, 7 }

Try it yourself

function setDifference(arr1, arr2) {
    const set1 = new Set(arr1)
    const set2 = new Set(arr2)
    const differenceSet = new Set();
    // Write your code here
    
    
    return Array.from(differenceSet);
}
quiz iconTest yourself

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

All lessons in Logic & Flow