Intermediate Algorithm Scripting - Seek and Destroy

Hi,
could any one explain why and how my code is wrong? it works for some cases only:

function destroyer(arr, ...args) {
 
for (const arg of args){
  for (let i=0; i<arr.length; i++){
    if (arr[i]===arg){
   arr.splice(i,1)}
  }
}
  return arr;
} 
destroyer()

console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3)); Woks
console.log(destroyer([3, 5, 1, 2, 2], 2, 3, 5)); shows [1,2] while should show [1]
console.log(destroyer([2, 3, 2, 3], 2, 3)); shows [3] while should show
thanks,

Your browser information:

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

Challenge: Intermediate Algorithm Scripting - Seek and Destroy

Link to the challenge:

I’ve edited your code for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (').

1 Like

Even without running your code, I get nervous when I see things like this:

  for (let i=0; i<arr.length; i++){
    if (arr[i]===arg){
      arr.splice(i,1)}
    }
  }

You are altering arr (using the splice method_) while you are indexing into that - and using the length to control the loop. These are both warning flags for me. If I were you, I would put some log statements in there and see what arr[i] is on each iteration and if it makes sense with the data.

1 Like

You are absolutely right. I got it. Thanks

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.