# Stumped on Seek and Destroy [Resolved] [Spoilers]

Stumped on Seek and Destroy [Resolved] [Spoilers]
0

#1

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 = arr.slice.call(arguments, 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 !
arr.splice(i,1);
}
}
}
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.

#2

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…

#3

You can test your code working in http://pythontutor.com/javascript.html#mode=edit
This will show up any problems.

#4

That was the problem! Thanks for pointing me in the right direction. I ended up just adding
`i--;`
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.

#5

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