Seek and Destroy - only first matching elements being removed - SOLVED

Tell us what’s happening:

Only the first elements that meet the criteria are being removed but the loop doesn’t continue until all matching elements are removed. How can this achieved?

Your code so far


function destroyer(arr) {
  let args = Array.prototype.slice.call(arguments)
  for (let i = 1; i < args.length; i++) {
    if (arr.includes(args[i])) {
      arr.splice(arr.indexOf(args[i]), 1)
    }
  }
  return arr
}

console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3))
console.log(destroyer([1, 2, 3, 5, 1, 2, 3], 2, 3))
console.log(destroyer([3, 5, 1, 2, 2], 2, 3, 5))
console.log(destroyer([2, 3, 2, 3], 2, 3))
console.log(destroyer(["tree", "hamburger", 53], "tree", 53))

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36.

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

It doesn’t continue because you’re iterating only 1 time on every argument. Try changing your if to a while, so it will keep removing elements while the arr has the element.

1 Like

It worked! Thank you!

function destroyer(arr) {
  let args = Array.prototype.slice.call(arguments)
  for (let i = 1; i < args.length; i++) {
    while (arr.includes(args[i])) {
      arr.splice(arr.indexOf(args[i]), 1)
    }
  }
  return arr
}