How to filter() out NaN, null, 0, false in an array (JS)

I am also working on the Free Code Camp Falsy Bouncer Algorithm. I have found the simplest way to do it is:

function bouncer(arr) {
   return arr.filter(Boolean);
}

Look at the docs for Array.filter. Notice in particular the arguments to the callback:

Function to test each element of the array. Invoked with arguments (element, index, array). Return true to keep the element, false otherwise.

So in your case arr is the element (and poorly named, hence your confusion). Filter loops through your array and for every item it calls you callback passing in the element at the current position as arr.

As others have pointed out in the comments, the logic of your filter callback is actually flawed for negative values, but that may not be an issue if you know that your array will never contain negative values (but that can be a dangerous thing to assume).

And, of course, internally, this is looping through your array. You can't filter your (unsorted) array without touching each element in the array. Look at the polyfil in the link to get an idea of how it might work (might because this is an implementation detail that may differ with different javascript engines, but will no doubt involve a loop somewhere), it loops through your array, calls the callback (note the arguments) and if the callback returns true, it gets pushed onto a results array.


You can also use an identity function instead of Boolean.

function bouncer(arr) {
  return arr.filter(x => x);
}

If you were asked to filter out NaN, null, 0, false in an array, then your solutions doesn't really work.

Your input of:

bouncer([0, 1, 2, 3, 'ate', '', false, NaN]);

Will get the output of:

[1, 2, 3, 'ate', NaN]

To filter out all 'falsy' values you can simply use Boolean:

function bouncer(arr) {
  return arr.filter(Boolean);
}

bouncer([0, 1, 2, 3, 'ate', '', false, NaN]);

Output:

[1, 2, 3, 'ate']

Since the Boolean constructor is also a function, it returns either true for ‘truthy’ argument or false for ‘falsy’ argument. If the value is omitted or is 0, -0, null, false, NaN, undefined, or the empty string (""), the object has the value of false. All other values, including any object or the string "false", create an object with an initial value of true.