Seek and Destroy, Why can I not do this?

Seek and Destroy, Why can I not do this?
0

#1

Why can I not do the Seek and Destroy challenge using the below code? It seems that the function compare is returning only 1 value even if there’s a loop. The code below returns an array [1,3,1,3] instead of [1,1]. Please help!

Your code so far


function destroyer(arr) {
  // Remove all the values
 
  var i;
  var arr2=[];
  var arr1 = arr.slice.call(arguments[0]);
  

 for(i=1; i<arguments.length; i++){
    arr2.push(arguments[i]);
    

  }
  return arr1.filter(compare);
  
  function compare(value){
    for (i=0; i<arr2.length; i++){
   return value != arr2[i];   
    }
  }
 
}


destroyer([1, 2, 3, 1, 2, 3], 2, 3);

Your browser information:

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

Link to the challenge:


#2

I have added some console.log statements through out your solution, so you can see the values of various variables and expressions used in your solution. With these console.logs, you should be able to isolate your logic error.

function destroyer(arr) {
  // Remove all the values
 
  var i;
  var arr2=[];
  var arr1 = arr.slice.call(arguments[0]);
  
  console.log('arr1 = ' + arr1)
  for(i=1; i<arguments.length; i++){
    arr2.push(arguments[i]);
  }
  console.log('arr2 = ' + arr2)
  console.log()
  return arr1.filter(compare);
  
  function compare(value){
    for (i=0; i<arr2.length; i++){
      console.log('value = ' + value + ' and arr2['+i+'] = ' + arr2[i]);
      console.log('value != arr2[' + i + '] evaluates to ' + (value != arr2[i]));
      console.log()
      return value != arr2[i];   
    }
  }
}

For the test of:

destroyer([1, 2, 3, 1, 2, 3], 2, 3);

the following is displayed in the console:

arr1 = 1,2,3,1,2,3
arr2 = 2,3

value = 1 and arr2[0] = 2
value != arr2[0] evaluates to true

value = 2 and arr2[0] = 2
value != arr2[0] evaluates to false

value = 3 and arr2[0] = 2
value != arr2[0] evaluates to true

value = 1 and arr2[0] = 2
value != arr2[0] evaluates to true

value = 2 and arr2[0] = 2
value != arr2[0] evaluates to false

value = 3 and arr2[0] = 2
value != arr2[0] evaluates to true

=> [ 1, 3, 1, 3 ]

Your compare function only makes it through one iteration before you return true or false. So if the first element in arr2 does not equal value, you are returning true and value gets added to the new array which will be returned back at the end. You need to use the “Return Early Pattern” you should have already learned in previous challenges.


#3

Thanks for this randelldawson. I know this is bad coding, I still do this most of the time, making a simple line of code more complicated tsk tsk! I managed to fix this by using indexOf, which I read from the hints section.