I think I'm so close to a solution, but I just can get it to work!

I’ve been trying for over an hour to get this code to work. Can someone please help me out?

function destroyer(arr) {	
for(var i=1; i<arguments.length; i++) { 

function x(value){
	console.log(i)
return value != remove}
filtered = arr
remove = (arguments[i])
filtered = arr.filter(x)
console.log(filtered)

}
  return filtered;
}

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

Hello !

There is much stuff going wrong in this piece of code, let me give you some pointers :

  • You should always prefix variables declaration with “var”, and declare them before using them!

  • For the sake of clarity, always end your statements with a semicolon.

What happens if you declare variables inside of a for loop ? What do you think it’s content is at, when the loop restart ?

1 Like

Hi,

You’re right - you’re almost there. What I always find helps when I’m stuck on something like that is to write more expressive console.logs, to drill into what’s going wrong.

I just did this with your code, I added lines like this

  console.log("filtered line 27: " + filtered)

so it would tell me what the value of filtered was at a specific line. Doing this I was able to find the mistake, I think. You set the filtered array correctly

  filtered = arr.filter(x)

But you never assign it to ‘arr’ so the next time it comes round the loop, it starts with the original array again, not the one you’ve just filtered. To fix it, you just need to add

arr = filtered;

before the end of the loop.

@Mizu’s points are valid (though it’s a bit harsh to lead with ‘there is much stuff going wrong…’ :slight_smile: ) You’ll save yourself a lot of pain if you make yourself declare variables explicitly - I find it’s best to add “use strict”; to everything to make myself do this because otherwise much confusion can creep in.

2 Likes

I really didn’t meant to be harsh, i’m sorry if it felt like so. Criticizing code is completely different than criticizing a person abilities imo.

1 Like

No problem. I decided that my JavaScript wasn’t really up to scratch, so I went away and did some other exercises, and not my confidence is much improved.