Falsy Bouncer - question about Array.prototype.filter()

Falsy Bouncer - question about Array.prototype.filter()
0.0 0

#1

I just solved the Falsy Bouncer challenge in the Basic Algorithm Scripting section, but I had another idea for a solution that doesn’t seem to work, and I’m wondering why.

Here’s the solution that worked:

[code]function bouncer(arr) {
function notFalsy(i) {
if(i !== false){
return i;
}
}
return arr.filter(notFalsy);
}

bouncer(variousArrays);[/code]

and the other solution, which I thought was simpler, but seems not to work:

[code]function bouncer(arr) {
function notFalsy(i) {
return i !== false;
}
return arr.filter(notFalsy);
}

bouncer(variousArrays);[/code]

This second solution was more in the vein of the leading example provided by MDN on Array.prototype.filter(), but it seems like maybe it doesn’t work the same way with boolean values. It seems to me like the two above solutions should be functionally the same and only syntactically different, but obviously that’s not the case.

Any help appreciated, thanks!


#2

So this:

i !== false

is only evaluating to true when i is actually the value false. In order to see whether i is “falsy” this way you would want to cast it to a Boolean

function bouncer(arr) {
  function notFalsy(i) {
    return Boolean(i) !== false;
  }
  return arr.filter(notFalsy);
}

would work.

So why does your first solution work? It’s actually making use of the “falsiness”/“truthiness” of each value. It’s this bit that does the work:

return i;

Extending that to your second approach, we get:

function bouncer(arr) {
  function notFalsy(i) {
    return i;
  }
  return arr.filter(notFalsy);
}

With an anonymous filter function we can make it:

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

Falsiness is cool.


#3

Thank you! That clears it all up.