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
EasyCreate 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
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);
}
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