Hi! Im making the Symmetric difference challenge. I created a code that resolves the symmetric difference for two arrays, but i don’t know how to use reduce to extend it two several variables.
It works only for two arrays sym(arr1,arr2). But i want that it works for several variables sym(arr1,arr2,arr3). I saw in the algorithms section that i can do with reduce , but i do not know how to do it in my code.
function sym() {
var args = Array.prototype.slice.call(arguments);
var flatArgs = args.reduce((a, b) => a.concat(b));
return flatArgs.filter(function( arrayValue ){
j = 0;
for (var i = 0; i < arguments.length; i++) {
if ( args[i].indexOf( arrayValue ) == -1 ) {
j++;
if ( j == arguments.length - 1 ) {
return arrayValue;
}
}
}
});
}
alert(sym([1, 2, 3], [5, 2, 1, 4], [1, 5, 6, 7]));
What happens here is the arguments are pulled into the args array.
Then, the args array is “flattened” into flatArgs array. (all values are concat into one array)
Finally, we run a filter function, which returns only the values that pass the test (reach the return arrayValue statement).
The way the function is written, a value is taken from the flatArgs array and checked against each array passed using indexOf. It’s only returned if .indexOf == -1 each time except once (meaning it only showed up in one of the arrays).
I can’t think of a much different way to solve the problem.