how to get the symmetric difference of two sets in javascript

To get the symmetric difference of two sets in JavaScript, you can use the new Set data structure introduced in ES6. Here's the approach:

index.tsx
const symmetricDifference = (setA, setB) => {
  let difference = new Set(setA);
  for (let elem of setB) {
    if (difference.has(elem)) {
      difference.delete(elem);
    } else {
      difference.add(elem);
    }
  }
  return difference;
};

const setA = new Set([1, 2, 3, 4]);
const setB = new Set([3, 4, 5, 6]);
const result = symmetricDifference(setA, setB);
console.log(result); // Set { 1, 2, 5, 6 }
409 chars
17 lines

In this code, we define a function symmetricDifference that takes two sets (setA and setB) as inputs. We create a new set difference with the values from setA. We then loop through each element in setB and check whether it exists in difference with the has method. If it does, we remove it from difference with the delete method; if it doesn't, we add it to difference with the add method. Finally, we return the difference set, which now contains the symmetric difference of setA and setB. We create two sets setA and setB, call the symmetricDifference function, and print the result to the console.

gistlibby LogSnag