Why is this not working

Tell us what’s happening:
I don’t know why the code is not returning anything and is returning an empty array. I’ve seen this code inside a function and it works but I don’t get why?

The code inside a function working:

'function diffArray(arr1, arr2) {
var newArr = [ ];

function onlyInFirst(first, second) {
// Looping through an array to find elements that don’t exist in another array
for (var i = 0; i < first.length; i++) {
if (second.indexOf(first[i]) === -1) {
// Pushing the elements unique to first to newArr
newArr.push(first[i]);
}
}
}

onlyInFirst(arr1, arr2);
onlyInFirst(arr2, arr1);

return newArr;
}’

Your code so far


function diffArray(arr1, arr2) {
var newArr = [];
for(let i = 0; i < arr1.length;i++){
  if(arr2.indexOf(arr1[i])===-1){
    newArr.push(arr1[i])
  }
} return newArr
}

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

Your browser information:

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

Challenge: Diff Two Arrays

Link to the challenge:

See below where I added console.log statements, so you can see the values being referenced in your if statement. In the test case you provided, there are no instances where arr2.indexOf(arr1[i]) evaluates to -1, so nothing gets pushed to newArr.

function diffArray(arr1, arr2) {
  var newArr = [];
  for(let i = 0; i < arr1.length;i++){
    console.log(arr2);
    console.log(arr1[i]);
    console.log(arr2.indexOf(arr1[i]));
    if(arr2.indexOf(arr1[i])===-1){
      newArr.push(arr1[i])
    }
  }
  return newArr
}

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