Diff Two Arrays - Help me understand why my code works

Hello All,

I knew that I wanted to .concat() the two arrays and remove any duplicates. So I ended up achieving that but now I have no idea why its working… At first I thought it was a glitch but then I ran it through brackets and it worked fine in there too. I think the finalArr array should have more variables than the two it has, but please help me understand this:

function diffArray(arr1, arr2) {
var newArr = [];
var finalArr = [];
newArr = arr1.concat(arr2);
newArr.sort();

for(var i = 0; i < newArr.length; i++){
if(newArr[i] === newArr[i+1]) {
newArr.shift(newArr[i]);
} else {
finalArr.push(newArr[i]);
}

}

return finalArr;
}

diffArray([“andesite”, “grass”, “dirt”, “pink wool”, “dead shrub”], [“diorite”, “andesite”, “grass”, “dirt”, “dead shrub”]);

Thank you guys!

What do you think happens here:

newArr.shift(newArr[i]);

and here:

i < newArr.length

Oh wow thank you for pointing that out! So essentially ‘i’ continues to rise as the array.length shifts down, meaning what used to be arr[1] becomes arr[0] after the original arr[0] gets shifted?

Yes.
And btw, .shift() doesn’t take parameters, it just removes first item from an array. So when you find two equal items, first item from the array gets removed, i now points to the next item, for loop continues, i gets incremented and now points to the next next item.

1 Like