Diff Two Arrays (Int. Algorithm Scripting)

Diff Two Arrays (Int. Algorithm Scripting)
0.0 0

#1

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]);


#2

I would avoid the use of splice in a looping solution.
The reason is that splice changes the content of the array, so when looping over you are effectively looping into a different array every time causing all sorts of inconsistencies.

Moreover if you don’t pass a the second deleteCount parameter to splice all the elements coming after the start will be removed.

You can simply “tweak” the logic of your function to avoid mutating the array but still using indexOf in a code that works as:

-loop into the first array
  ---if the item is not present push it into a new array
-loop into the second array
  ---if the item is not present push it into the new array

new array should contains the numbers that are differents

Hope it helps :slight_smile:


#3

Marmiz,

Thanks for the response and assistance. While I was aware that splice changed an array, I thought it was contained in my loop and didn’t recognize the impact it was having on the results.

Thanks again,