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
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.
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.