Menu
Coddy logo textTech

Math - Symmetric Difference

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

The symmetric difference of two sets A and B is a new set that contains elements that are in either A or B, but not in both. It can be thought of as the union of A - B and B - A.

For example:

const set1 = new Set(arr1);
const set2 = new Set(arr2);

// Create symmetric difference
const symmetricDiff = new Set([
  ...set1.difference(set2),
  ...set2.difference(set1)
]);

// Convert back to array
const result = Array.from(symmetricDiff);
challenge icon

Challenge

Easy

Create a function called efficientSymmetricDifference that takes two arrays as parameters: arr1 and arr2. The function should convert the arrays to sets. Create a new Set that is the symmetric difference of the two input Sets, convert it to array and return the array

Cheat sheet

The symmetric difference of two sets contains elements that are in either set, but not in both. It's the union of A - B and B - A. For example:

// Convert arrays to sets
const set1 = new Set(arr1);
const set2 = new Set(arr2);

// Create symmetric difference
const symmetricDiff = new Set([
  ...set1.difference(set2),
  ...set2.difference(set1)
]);

// Convert back to array
const result = Array.from(symmetricDiff);

Try it yourself

function efficientSymmetricDifference(arr1, arr2) {
    const set1 = new Set(arr1)
    const set2 = new Set(arr2)
    const symDiff = new Set();
    // Write your code here


    return Array.from(symDiff);

}
quiz iconTest yourself

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

All lessons in Logic & Flow