Seek and Destroy Challenge: Help with loops and filter method

Hello guys! I am trying to resolve this challenge , even though I can get the resolutions, I would like to fix mine, so I can learn from my mistakes.

This is my code:

Blockquote
function destroyer(arr) {
for(var i=1;i<arguments.length;i++){
var result=arr.filter(item=>item!==arguments[i]); } return result; }
console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3)); output: [ 1, 2, 1, 2 ]

It destroys the “3”, but it doesn’t with “2”, what is missing? I wholeheartedly appreciate your support on this.

The issue here is, each time through the loop, you reference the original array, with all the elements still in.

How about this: before the loop, clone the array into result. Then, inside the loop, set result to the filtered subset of result.

1 Like

It works! Thanks a lot!

1 Like

Glad to help, you were very close before my suggestion. Keep up the great work!

1 Like

My updated code:

Blockquote
function destroyer(arr) {
var result=arr.slice(0,1);
for(var i=1;i<arguments.length;i++){
var last=result.filter(item=>item!==arguments[i]);
}
return last;
}

console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3));Output: [ 1 ];

Here I should get [1, 1] , but I only get [1], any suggestion?

@ snowmonkey

Two things: first, what do you think the parameters on your slice function are doing? And second, inside the loop, you’re referring to the original, unfiltered result array. Try simple setting result = result.filter(...) in the loop, setting result to the filtered version of itself?

As to the first question, the parameter to slice are begin index, (optional) end index. You’re asking to copy arr from 0 to 1st index…

1 Like

Blockquote
function destroyer(arr) {
var result=arr.slice(0);
for(var i=1;i<arguments.length;i++){
var result=result.filter(item=>item!==arguments[i]); }
return result; }

destroyer([1, 2, 3, 1, 2, 3], 2, 3); output: [1,1]

Great! Thanks for my improvement, I think the mistake was I forgot to make a copy of the new array and the assigment issue. Have a great day @snowmonkey

1 Like

Nicely done! Remember, if you post your lesson solutions, to blur them out. If someone comes in looking for help and instead find a complete working solution…

2 Likes