mso4491
mso4491

Reputation: 171

Remove Falsy Values from Array

So I am doing the FreeCodeCamp challenge "Remove all falsy values from an array."

I made a function, but for some reason it does not filter all the falsy values:

function bouncer(arr) {

function truthy(value) {
 return value !==  '' ||false || null || undefined || NaN ;
}

 var filtered = arr.filter(truthy);
 return filtered;
}

bouncer([7, "ate", "", false, 9]);

This should return

[7, "ate", 9], 

but instead returns

[ 7, 'ate', false, 9 ]

If I switch the order of the function truthy, the returned values changes. For example moving the '',

function truthy(value) {
   return value !==  '' ||false || null || undefined || NaN ;

----->

  return false || null || undefined || NaN || " ; 

The new

false || null || undefined || NaN || " ; returns

[ 7, 'ate', '', 9 ]

Any idea what is going on??? Thanks!

Upvotes: 0

Views: 922

Answers (3)

Ori Drori
Ori Drori

Reputation: 192517

In addition to AuxTaco's answer...

  1. "All falsy values" include 0 as well.

  2. You can shorten the filter expression a bit further, by using Boolean as function:

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

console.log(bouncer([7, "ate", "", false, 9, 0, NaN, null, undefined]));

Upvotes: 1

AuxTaco
AuxTaco

Reputation: 5181

return value !== '' ||false || null || undefined || NaN ;

This does not do what you think it does. It's actually equivalent to

(((((value !== '') || false) || null) || undefined) || NaN)

When value !== '', as in most of your cases, this expression is true. You would actually need to check

value !==  '' && value !== false && value !== null && value !== undefined && value !== NaN

But since these are all falsy anyway and Array.filter only cares about truthiness and falsiness, you can replace your truthy function with

function truthy(value) {
  return value;
}

which isn't even worth breaking out three lines for:

var filtered = arr.filter(e => e);

Upvotes: 5

Marcelo Origoni
Marcelo Origoni

Reputation: 318

The problem is, your return statement, will always return true when the value is different than blank

function truthy(value) {
    return value !==  '' ||false || null || undefined || NaN ;
}

should be something like this

function truthy(value) {
    falseValues = ['',false,null,undefined,NaN];
    return !falseValues.contains(value);
}

Upvotes: -1

Related Questions