Diff Two Arrays - Not passing FCC test 12 and 13

Tell us what’s happening:
My output looks correct but it still tells me that it’s not. Any ideas?

Your code so far


function checkArray(arr1, arr2, newArr) {
for (let i = 0;i < arr1.length; i++) {
  for (let j = 0; j < arr2.length; j++) {
   if (arr1[i] == arr2[j]) { // if equal
      break; // we disregard that element in arr1 and move to the next.
    } else if (j === arr2.length -1) {
      
       newArr.push(arr1[i]);
    }

  }//end of inner for loop
}//end of outer for loop
}//end of function

function diffArray(arr1, arr2) {
  var newArr = [];
  // Same, same; but different.
  if (arr2 == undefined) {
    return arr1;
  }

checkArray(arr1, arr2, newArr);
checkArray(arr2, arr1, newArr);

 return newArr;
}
 
console.log(diffArray( ["snuffleupagus", "cookie monster", "elmo"]));     

Your browser information:

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

Challenge: Diff Two Arrays

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

What do the failing tests say?

[], ["snuffleupagus", "cookie monster", "elmo"] should return ["snuffleupagus", "cookie monster", "elmo"] .

[], ["snuffleupagus", "cookie monster", "elmo"] should return an array with three items.

for (let i = 0;i < arr1.length; i++) {

All of your logic takes place inside this loop, but when arr1 is [] the loop never executes because arr1.length is 0.

Hey thank you for the response. Actually if you run the program you will find it works on every particular and passes 13 of the 15 FCC test for this challenge.

However on the test noted above, it fails on those two particular test even though my console.log shows the correct output. The function that has the for loop that contains my logic never sees the light of day if arr2 in diffArray is undefined (as far as I can tell).

You have nested loops in checkArray. If arr1 is [], then the outer loop never executes and nothing happens. If arr2 is [], then the inner loop never executes and nothing happens.

1 Like

I got it. I overlooked the fact that it was actually two arrays that were being fed into the function, one with 0 length. Your answer helped me realize that.Thanks again!

I’m glad I could help. Happy coding!