Diff Two Arrays returns undefined

Tell us what’s happening:

Your code so far


function diffArray(arr1, arr2) {
  var newArr = [];
  for (var i=0; i<arr1.length; i++){
  if (arr1.indexOf(arr2[i])===-1){
    newArr.push(arr2[i]);
  }
  }
    for (var j=0; j<arr2.length; j++){
  if (arr2.indexOf(arr1[j])===-1){
    newArr.push(arr1[j]);
  }
  }
  // Same, same; but different.
  console.log(newArr);
}

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

Why is it returning [4, undefined] ? wheres my mistake?

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/diff-two-arrays

The two arrays may differs in length, like in the example you provided.

[1, 2, 3, 5] // length 4
[1, 2, 3, 4, 5] // length 5

When you loop in the bigger one, (in this case the second one) you will go outside of the smaller array, accessing that value return undefined.

for (var j=0; j<arr2.length; j++) {
  console.log(arr1[j]) // J will go up to 5, but arr1 has 4 elements
}

// 1, 2, 3, 5, undefined

And your condition arr2.indexOf(arr1[j])===-1 is true, so you push undefined into newArr.

Hope this helps :+1:

1 Like