Symmetric Difference Help

Symmetric Difference Help
0

#1
function sym(args) {

  var arr = Array.prototype.slice.call(arguments);
  var diff = [];

  // removes duplicate numbers from first two arrays
  arr[0] = arr[0].filter((i, pos) => arr[0].indexOf(i) === pos);
  arr[1] = arr[1].filter((i, pos) => arr[1].indexOf(i) === pos);

  // calculates the difference of two arrays
  diff = diff.concat(arr[0].filter(e => arr[1].indexOf(e) === -1));
  diff = diff.concat(arr[1].filter(e => arr[0].indexOf(e) === -1));

  // removes first two arrays and puts difference in first place
  arr.splice(0, 2, diff);

  // if there is only one array(diff) as argument, return it
  if(!arr[1]) {
    return diff.sort((a,b) => a>b);
  }

  // else run sym() again
  sym(diff, arr[1], arr[2], arr[3], arr[4], arr[5]);

}

sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3], [5, 3, 9, 8], [1]);

I tried to write something that looks like recursive function and it works, but when I try to return the final result (sorted diff array) it returns undefined.

If I write diff inside console.log before return it logs diff without mistake… // [ 1, 2, 4, 5, 6, 7, 8, 9 ]

What is the problem?


#2

The last section of your code is missing a return statement. You could either do:

  // if there is only one array(diff) as argument, return it
  if(!arr[1]) {
    return diff.sort((a,b) => a>b);
  }

  // else run sym() again
  return sym(diff, arr[1], arr[2], arr[3], arr[4], arr[5]);

OR

  return !arr[1] ? diff.sort((a,b) => a>b) : sym(diff, arr[1], arr[2], arr[3], arr[4], arr[5]);

NOTE: Your solution works as long as the number of arrays sent to the function is not greater than 7. What would you do if you needed to find the difference of 1,000,000 arrays? See if you can figure out how to solve the problem to handle an unknown number of arrays passed to the function.


#3

Thanks for reply!

I know that this code is limited to certain number of arrays, but I can’t figure out how to handle arguments object to return simple array instead of 2D, 3D array and so on, on each recursion.