Symmetric Difference Project Tests and commutativity

Tell us what’s happening:
Two things regarding my code for the symmetric difference problem:

  1. I think my code is correct and I am at a loss as to why it is not passing. My reasons for believing it is correct is that it matches the results of randomly selected online symmetric difference calculators and what I carry out on paper. It also matches the result of the example in the linked video on the problem page.

  2. Even though my code yield what I expect, it is non-commutative. Which is to say that if I put he same arrays into the function in a different order I get a different result. My concern is that everything I’ve read online says symmetric difference operation should commute. However, when I carry out symmetric difference by hand as per the video’s example, I cannot show commutative properties either.

I think that either 1) I do not fully understand symmetric difference (most probable), or 2) the test cases in the problem are incorrect (I’m currently passing all except three test cases).

I’ve spent an embarrassing amount of time on this problem, any help would be greatly appreciated.

Your code so far

  var comp = arr1.concat(arr2);
  var symDiff = [];
  for (var i in comp) {
    if (arr1.indexOf(comp[i]) == -1 || arr2.indexOf(comp[i]) == -1) {
      symDiff.push(comp[i]);
    }
  }
  return symDiff;
}

function sym() {
  var symDiff = arguments[0];
  for (var i = 1; i < arguments.length; i++) {
    symDiff = symDiffTwo(symDiff, arguments[i]);
  }
  return symDiff;
}

sym([3, 4, 5, 5], [1, 1, 2, 5], [2, 2, 3, 5]);

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36.

Link to the challenge:
https://www.freecodecamp.org/challenges/symmetric-difference

Can you edit your code to show the function declaration for symDiffTwo? It appears to have been cut off when the post was created.

EDIT: I assume your symDiffTwo delcaration line looks like:

function symDiffTwo(arr1, arr2) {

If the above is true, then the bigger issue you are having is that your result does not reflect a set, which is a collection of unique elements. This means there should be no duplicates in the final solution. Also, the order of a set is not important. I you compare a set of 1, 4, 5 to 5, 4, 1, they are considered the same set. The order changes when you change the order of the arrays called as arguments to the sym function, but the final array (set) will contain the same elements no regardless of the order.

Thank you! Yes, it was simply a matter of deleting duplicates in the set resulting from each symmetrical difference operation. I did not know this aspect of set theory, but it is now obvious why this operation is commutative once this is known.