# Diff Two Arrays - why doesn't this work?

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

for (i = arr3[0]; i < arr3.length + 1; i++) {
if (arr3[i] !== arr3[i+1] && arr3[i] !== arr3[i-1])
newArr.push(arr3[i]);
}
return newArr;
}

diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);
``````

What is the problem asking for? When I ran your code I got [4] which is the only difference between the arrays.

I’ve edited your post for readability. When you enter a code block into the forum, precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (`</>`) will also add backticks around text.

sorry…this is the intermediate algorithm. This is the problem…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.

It worked for those two specific arrays but not for some of the other arrays in problem ie. [“diorite”, “andesite”, “grass”, “dirt”, “pink wool”, “dead shrub”], [“diorite”, “andesite”, “grass”, “dirt”, “dead shrub”]

This one did not work.

There’s something very wrong about this line: `for (i = arr3[0]; i < arr3.length + 1; i++)`

You’ve set `i` to be the first element of the array, and then incremented it, which I definitely don’t think you meant to do. I think it’s just a happy little accident that it worked for some cases.

Also `i < arr3.length + 1` seems very wrong to me, what is `arr3[arr3.length]`?

I suspect you intended to do `for(i=1; i < arr3.length - 1; i++)` (based on using`i+1` and `i-1`)

gebulmer…Thank you for the help.

The solution that works includes this:
for (i=0; i<arr3.length; i++)