javascriptalgorithmsymmetric-difference

Find symmetric difference between two arrays


I'd like to find the symmetric difference between TWO arrays. This implementation works, however I'd like to write a function that is specific to only two arrays, rather than one that finds the symmetric difference between a bunch of arrays. The function should like this:

function diffArray(arr1, arr2) { }

then return a new array with the symmetric difference.

My best attempt so far was

var newArr = [];
    for (var i = 0; i < arr1.length; i++){
      var x = arr[i]; 
    for (var n = 0; n < arr2.length; n++){
      var y = arr2[n];
      if (y === x){
        break;
       } else {
      newArr.push(y);
    }
  }
 }

However, I know this is not even close. The question (it is an algorithm problem for FreeCodeCamp) hints to use the methods array.filter(), array.indexOf(), array.concat(), array.slice() in the implementation. I understand that the general idea is to take each element in one of the arrays (the first one in my case), then compare it to every element in the second array. If no matches are found, push that element into the newArr.

Can anyone help with a sound implementation that uses the aforementioned methods and provide a solid explanation/comments on how it works?

Thank you!


Solution

  • Here is another idea:

    function diffArray(arr1, arr2) {
        var newArr = [];
    
        return arr1.filter(function(val) {
            return arr2.indexOf(val) === -1;
        })
        /*the method above, returns a new array, so you can chain it
              to concat with the array returned from the filter() method
              in the arr2...*/
    
            .concat(arr2.filter(function(val) {
                return arr1.indexOf(val) === -1;
            }));
    }