Seek and Destroy - Why is filter needed here?

Regarding the last line in the function,

Why do I need

return arr.filter(item=>item);

I believe the solution works but if I use

return arr

it does not work. Why is filter required here, it only appears to check each element in the array named arr and output the same element

Your code so far

function destroyer(arr) {
    for (var i = 0 ; i<arr.length ; i++) {
      for (var j = 0 ; j<arguments.length ; j++) {
        if (arr[i]===arguments[j]) {
          delete arr[i];
  return arr.filter(item=>item);

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

Your browser information:

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

Link to the challenge:

arr.filter(item=>item) will filter each item by its own “truthiness” value. So if an item is 0, empty, false, or any other “falsy” value, it will not pass the filter criterion, and thus not be included in the output.

1 Like

Thanks. To clarify, delete arr[i] means that arr[i] is a falsy value so .filter is used to remove any falsy values. Is this correct?

Check for yourself, use console.log(arr) before filter is used

Let’s go into a long-form explanation for posterity: The Array.filter method is given a callback function, i.e.


In this case, imagine a function called identity that just takes a value and returns it. Doesn’t seem useful by itself, but wait for it:

function identity(x) { return x; }

So now you have this:


If you treat it as a function returning true or false values, any value in that’s false (“falsey” actually, as explained in the challenge) will return itself, and therefore a false value.

A shorter version of this, as an expression, is just x => x. So now you have this expression:

arr.filter(x => x)

Which should do the same as the longer version using identity. For each value in the array, it’s passed to the callback function, and if it returns false, it is omitted from the return value.