# Symmetric Difference Help

``````function sym(args) {

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

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

// calculates the difference of two arrays
diff = diff.concat(arr.filter(e => arr.indexOf(e) === -1));
diff = diff.concat(arr.filter(e => arr.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) {
return diff.sort((a,b) => a>b);
}

// else run sym() again
sym(diff, arr, arr, arr, arr, arr);

}

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

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?

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) {
return diff.sort((a,b) => a>b);
}

// else run sym() again
return sym(diff, arr, arr, arr, arr, arr);
``````

OR

``````  return !arr ? diff.sort((a,b) => a>b) : sym(diff, arr, arr, arr, arr, arr);
``````

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.

1 Like