The Seek and Destroy algorithm challenge: Why is my filter not working?

To put it simply, I’ve never yet managed to get the filter() method work for me. In the Seek and Destroy challenge, I start by separating the argument into the array itself, to be filtered (firstArray in the code below) and the other arguments to be filtered out (everythingElse). Then I try to filter firstArray to weed out everythingElse, as shown below:

function destroyer(arr) {
  var firstArray = [];
  var everythingElse = [];
  for (i = 0; i < arguments.length; i++) {
    if (i === 0) {
      firstArray.push(arguments[i]);
      
    } else {
      everythingElse.push(arguments[i]);
    }
  }
// Everything seems to work up to here.

function allowedItem (value) {
  for (b = 0; b < everythingElse.length; b++) {
    var toBeTested = everythingElse[b];
    return value !== toBeTested;
  }
}

firstArray = firstArray.filter(allowedItem);
return firstArray;
}

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

Am I right that the “value” in filter() refers to values in the array that is being filtered? The code above doesn’t filter anything out; apparently, every value in firstArray somehow finds a match among the 2 and 3 in everythingElse. Does anyone have any idea as to why?

I’m not positive, but I think here’s what’s going on:

  1. Your function allowedItem() needs a return, right? It iterates over the first array and “returns” anything that satisfies its criteria.
  2. But the return there is inside the for loop! Each iteration of allowedItem contains multiple iterations through this for loop. This seems to be where it’s not working–but you wouldn’t even want your allowedItem() to push the same value multiple times, for every entry in everythingElse!
  3. May I interest you in the array method .includes()? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

One more thing. Maybe instead of firstArray.push(arguments[i]);, you want firstArray = arguments[i];. With your current code, the value of firstArray is actually something like [[1, 2, 3, 5, 1, 2, 3]] (an array in an array), not [1, 2, 3, 5, 1, 2, 3].

1 Like

Thanks for introducing me to includes(). I’ll keep it in mind the next time I see a problem like this, even though, in this case, I solved the challenge as follows:

function destroyer(arr) {
  var firstArray = [];
  var everythingElse = [];
  for (i = 0; i < arguments.length; i++) {
    if (i === 0) {
      firstArray = arguments[i];      
    } else {
      everythingElse.push(arguments[i]);
    }
  }

function allowedItem (value) {
  return everythingElse.indexOf(value) === -1;
}
return firstArray.filter(allowedItem);
}

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