Stumped on Seek and Destroy [Resolved] [Spoilers]

Having a problem I can’t figure out. My seek and destroy code passes the first, second and fifth test, but fails the 3rd and 4th

My code

function destroyer(arr) {
  // Remove all the values
  // isolate targets
  var targets =, 1);
  // Establish counters
  var count = targets.length;
  var cycle = arr.length;
  // Set outer loop
  for (var i = 0; i < cycle; i++) {
    // Set inner loop
    for (var j = 0; j < count; j++) {
      // Searching....
      if (arr[i] === targets[j]) {
        // Seek and destroy ! 
  return arr;

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

The case of destroyer([3, 5, 1, 2, 2], 2, 3, 5)
Returns [1,2] instead of just [1]

I am sure there are 100 more slick ways to solve it, but this is the first solution that came to mind and I’m at a loss how it works for some values and not for others.

the problem in your algo is the line “arr.splice(i,1)” (you manipulating/cutting your result array while iterating over it, this will lead definitely to a index clash issue)! just place a “console.log(arr[i] + " " + targets[j])” right before your if statement and you will see what happens…

1 Like

You can test your code working in
This will show up any problems.

That was the problem! Thanks for pointing me in the right direction. I ended up just adding
Right after the splice line to adjust for the shorter length of the array.

Now that I made it work I can go look at other solutions and feel like an idiot all over again…
Thanks again for the help.

1 Like

Added spoiler to the original post title… takes me awhile sometimes to catch on to the local customs…
Also, it looks as if I could have avoided the index issue if I set the loop to iterate in reverse… live and learn