Seek and Destroy pushes all elements

Tell us what’s happening:
Can someone please tell me why its pushing All the elements from arr1 into newArr instead of doing what I want it to do, and only push the elements that are not found in arr2, please explain my mistake.

Your code so far


function destroyer(arr) {
  var newArr=[];
  var arr1= arguments[0];
  var arr2=[];
  //get the second pair of args till the end:
  for (var i=1; i<arguments.length; i++){
    arr2.push(arguments[i]);
  }
  //if any of the elements in arr1 do not exist in arr2 push those elements into newArr
    for (var j=0; j<arr1.length; j++){
  if (arr2.indexOf(arr1[j]===-1)){
    newArr.push(arr1[j]);
  }
  }
  console.log(newArr);
  // Tobdestroyed.filter(function(x){
  //   return x
  // })
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);

Your browser information:

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

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/seek-and-destroy

Edit: I now see I made a syntactic error, I have since fixed it, and solved this problem however I want to know why the error I made in typing (arr2.indexOf(arr1[j]===-1)) and putting the parenthesis in the wrong place, caused the statement to always evaluate to true, and push every element

When you write: arr1[j] === -1 each iteration was comparing the value of arr1[j] to -1. Since none of the arr1[j] values were equal to -1, then this comparison evaluated to false. The indexOf method was checking if any element in arr2 was the value false. The indexOf method returns a value of -1 if no index has the an element with the value specified, so your if statement was the equivalent of:

if (-1) {
  newArr.push(arr1[j]);
}

All numeric values which are not the value 0 are truthy, so your if statement evaluated to true each time, so you pushed all the values of arr1 into newArr.

1 Like