Skip to main content

JavaScript Function For Symmetric Difference

EDIT: Note that the code below works (at least as far as I know) so long as you assume each array is formatted like a set.  If either of the arrays have repeating entries -- i.e. behave the way arrays are allowed to behave -- the algorithm won't work and is seriously in error.  Oh well -- back to the drawing board.

The symmetric difference of two sets is the difference between their union and their intersection. Consider the following sets:
A = {1, 2, 3, 4, 5}
B = {1, 3, 5, 7, 9} 
The union of A and B is
{1, 2, 3, 4, 5, 7, 9}.
The intersection of A and B is
{1, 3, 5}.
So the symmetric difference of A and B is
{1, 2, 3, 4, 5, 7, 9} - {1, 3, 5} = {2, 4, 7, 9}.
My job was to construct a two argument JavaScript function that would correctly return this result.  I decided to proceed as follows:
1. Concatenate the two arrays to produce their "union" (with duplicate values).
2. Remove any value that has a duplicate.
Here is my code:
function diffArray(arr1, arr2) {
  var newArr = arr1.concat(arr2);
  newArr = newArr.filter(function (value, index, array) {
                elOut = array.slice(0,index).concat(array.slice(index+1,array.length));
  return elOut.indexOf(value) == -1;
                });
  return newArr;
}
The function diffArray() takes two arrays as arguments (no debugging for non-array inputs).  It concatenates them together as newArr.  Then it runs newArr through the function filter().  From what I can tell, this function is going through each element of the newArr and returning it if and only if it passes a Boolean test.  Calling the function accordingly gives me three variables to work with: the index of the array being examined, the value of that index, and the array itself.

So what I wanted to do was consider whether, for a given item in the array, a duplicate of that item was present in the array.  Using the method indexOf(), I knew I could search an array and get the position of a given value.  The problem was that I needed the index of the duplicate of the value I was searching for and not the value itself -- searching in newArr wouldn't work.  The solution was to take the value I was searching for out of the array.  To do so, I sliced the array on the index of that value, forming a new array, elOut ("Get the element out!")  I then had the callback return False (-1) if the value was still present in elOut.  Reconstructing newArr to include only those elements that passed the test, I was then able to fulfill the requirements of the assignment.

Comments