I’ll admit to a click-baity title here, but I would like some help thinking through the solution I came up with for the Diff Two Arrays scripting challenge.
I’ve included my script below. Technically, it passes all of the tests. However, instead of returning just one instance of the symmetric difference of the two arrays, it returns that instance the equivalent number of times as the length of my concat array (newArr). With the diffArray below the solution should be [4, 6]. But my script returns [4,4,4,4,4,4,4,4,4,4,6,6,6,6,6,6,6,6,6,6].
I can’t figure out what is causing this repetition. Please help.
function diffArray(arr1, arr2) {
var newArr = [];
var solution = [];
//Merge both subarrays into one unified array
newArr = arr1.concat(arr2);
var sorting = newArr.filter(function (elem) {
for (var i = 0; i < newArr.length; i++) {
if (arr1.indexOf(elem) < 0 || arr2.indexOf(elem) < 0) {
solution.push(elem);
}
}
});
return solution;
}
diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5, 6]);