Reputation: 792
I'm trying to solve a coding challenge from Free Code Camp.
Diff Two Arrays
Compare two arrays and return a new array with any items only found in one of the two given arrays, but not both. In other words, return the symmetric difference of the two arrays.
[1, 2, 3, 5], [1, 2, 3, 4, 5] should return [4].
[1, "calf", 3, "piglet"], [1, "calf", 3, 4] should return ["piglet", 4].
My code is below:
function diffArray(arr1, arr2) {
var arr1Key = [];
arr1Key = arr1;
for (i = arr1.length - 1; i >= 0; i--) {
for (j = 0; j < arr2.length; j++) {
if (arr1[i] === arr2 [j]) {
arr1.splice(i, 1);
}
}
}
for (k = arr2.length - 1; k >= 0; k--) {
for (l = 0; l < arr1Key.length; l++) {
if (arr2[k] === arr1Key[l]) {
arr2.splice(k, 1);
}
}
}
var newArr = [];
newArr = arr1.concat(arr2);
return (newArr)
}
diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);
I know it's probably not perfect/optimal, but what I primarily want to know is why my first series of for loops (using i & j) works perfectly. Meanwhile, my next series of for loops (using k & l) is a nearly identical copy of the first, but after some testing I found that only the k for loop works. The l for loop isn't working, and I don't understand why.
I've been staring at this thing and tinkering with it for what feels like forever and I just don't understand.
Upvotes: 0
Views: 63
Reputation: 1563
The problem is that you think you clone arr1
by writing arr1Key = arr1;
This does not clone but creates a reference to arr1
, so arr1.splice(i, 1);
changes also arr1Key
.
Just change the line arr1Key = arr1;
into arr1Key = arr1.slice();
Upvotes: 1
Reputation: 1634
You are splicing the arrays while looping through them, splicing can make them grow or shrink and you don't want that because you are using the array's length
to loop.
Upvotes: 1