I am not receiving the results I expected on my Diff Two Arrays code, and would appreciate feedback.
My general approach was to loop through array 2 and compare each value to array 1, to determine if the value is unique or whether it also exists in array 1. If it doesn’t, and it is unique, the value is pushed to a new array (array 3). If it it isn’t unique, then I remove (splice) the non-unique value from array 1. After completing the loop, I concatenate array 3 (which consists of the pushed unique values) and the remainder of array 1 (which consists of unique values not spliced).
The comparison loop works properly for the first one or two comparisons (i = 0, i = 1), and then fails on the third value and beyond (i = 2, and beyond). If I rotate the values in the array, I see that values that incorrectly compare, now correctly compare, and vice versa.
I’ve tried this as a for loop and a switch, and receive identical results. Here is the code using switch. Using this, it returns: [2, 3, 4, 5]
Thanks in advance for your feedback.
function diffArray(arr1, arr2) {
var newArr = [];
var arr3 = [];
for (i = 0; i < arr2.length; i++) {
switch(arr1.indexOf(arr2[i])) {
case -1:
arr3.push(arr2[i]);
break;
default:
arr1.splice(arr1.indexOf(arr2[i]));
}
}
newArr = arr1.concat(arr3);
return newArr;
}
diffArray([1, 2, 3, 5, 6], [1, 2, 3, 4, 5]);