My Own Code: Seek and Destroy condensed

My Own Code: Seek and Destroy condensed
0

#1

Hello! I have been going back through the algorithm problems and attempting to clean up and condense the code as much as I can. I went back through this one and found a neat way to filter through the argument arr with the given parameters. On the results page when finding the more advanced answers for these questions this style of coding the answer wasn’t on there. Let me know if there is anything else I could condense down or tweak to make this even cleaner. Thanks in advance!

function destroyer(arr) {
return arr.filter(function(value) {
return this.indexOf(value) <0;
}, Array.prototype.slice.call(arguments).slice(1));
}


#2
function destroyer(arr) {
  return arr.filter(v => !~[].slice.call(arguments).indexOf(v));
}

#3

Thanks for the reply! a lot of stuff there that I don’t know. If you have the time I would appreciate an explanation of how the code works. Specifically “v => !~[]”


#4

Yah I just copied this from my own fcc challenge since I was in a hurry sorry for that

[].slice.call(arguments) // is the same as Array.prototype

The tilde is a little more complex to explain but it is easy to understand, basically when using with indexOf it will return true if it founds the value and false otherwise. You can read a better explanation here https://github.com/getify/You-Dont-Know-JS/blob/master/types%20%26%20grammar/ch4.md#the-curious-case-of-the-

And the ! I am just negating the expression since I want to filter the elements that ~ match. So, if ~ returns true it means I want to destroy this element, so I negate it with ! to make it false so filter won’t include it.

The v => ... is just an es6 arrow function, it’s the same as calling function (v) { return ... }

Hope it helps :wink:


#5

That helps a ton, thank you! I definitely get it after your explanation. It was the es6 notation that was tripping me up the most since I’ve never seen that. I appreciate the help!