Diff Two Arrays

Hi Everyone,

My code for the Diff Two Array Algorithm challenge works for each of the test cases that are listed, but yet they all show a red X’s. I’ve also tested my code locally and it works fine. I can’t understand why it keeps failing, my results are correct each time. Maybe I’m missing something.

Any suggestions?

My code:

var diff = [];
function diffArray(arr1, arr2) {
var length = Math.max(arr1.length, arr2.length);
if (!(arr1.length === 0 || arr2.length === 0)) {
for (i=0;i<length;i++) {
if (arr1.indexOf(arr2[i]) < 0 && arr2[i] !== undefined) {
diff.push(arr2[i]);
}
if (arr2.indexOf(arr1[i]) < 0 && arr1[i] !== undefined) {
diff.push(arr1[i]);
}
}
}

if (arr1.length === 0) {
  for (i=0;i<arr2.length;i++) {
    diff.push(arr2[i]);
  }
}

if (arr2.length === 0) {
   for (i=0;i<arr1.length;i++) {
    diff.push(arr1[i]);
   }
}

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

Your first statement - var diff = []; - should be inside the function. If it is outside, it is global so it never gets cleared, it just keeps adding onto the values from the previous test runs and getting bigger and bigger. If it’s inside the function, then it gets destroyed when the function is left and recreated when the function is called again. Alternatively if you really, really wanted to have it global, you could clear it each time you call the function. But putting it inside the function is cleaner and more standard.

@ksjazzguitar - Thank you, that fixed the problem. I moved var diff = []; to inside the function and it passed all of the tests. I can’t believe that was it. THANK YOU!

Sure, it’s easy to make mistakes like that. (I’ve probably made this exact mistake before, probably a few times.) That’t the frustration and joy of coding. Just be sure that you understand why it worked that way. Every mistake is a chance to get a deeper understanding.