mardi 19 juillet 2016

Conditional loop not working as expected

I am following courses in FreeCodeCamp to learn Javascript. I am in "Diff in Two Arrays". Assignment is comparing two arrays and return a new array with any items only found in one of the two given arrays, but not both.

Below is the code I try to compare them, second part does not apply. I want to undertand why second part of the conditional loop does not work.

function diffArray(arr1, arr2) {
  var filtered = [];
  var l = 0;
  newArr = Array.prototype.slice.call(arguments);
  for (var j=0; j < newArr.length; j++){
    for (var k=0; k < newArr[j].length; k++){
       //values to check before and next index 
       l  = j + 1;
       var m = j-1;
       if (l < newArr.length){
            if (newArr[l].indexOf(newArr[j][k]) === -1){
                filtered.push(newArr[j][k]);
            } else if (j == newArr.length - 1){ // this part does not work
                console.log(j);
                if (newArr[m].indexOf(newArr[j][k]) === -1 ){
                    console.log(newArr[j]);
                    filtered.push(newArr[l][k]);
                }
            }        
         }
       }
    }
  // Same, same; but different.
  return filtered;
}

diffArray([1, "calf", 3, "piglet"], [1, "calf", 3, 4]);

Thanks.

Aucun commentaire:

Enregistrer un commentaire