简体   繁体   中英

Javascript filter function to filter out falsy values

I am learning javascript and have the following code to filter out falsy values from a string.

function isFalsy(value) {
  if(value === false) 
    return false;
  if(value === null)
   return false;
  if(value === 0)
   return false;
  if (value ==="")
   return false;
  if (value === undefined)
   return false;
  if(value.isNaN)
   return false;

  return true;

}
function bouncer(arr) {

  arr = arr.filter(isFalsy);
  return arr;
}

I run the following:

bouncer([1, null, NaN, 2, undefined]);

I except the result to be:

[1,2] 

but it gave me

[1,null, 2]

What is going on?

The problem isn't null , it's NaN ; proof:

 function isFalsy(value) { if(value === false) return false; if(value === null) return false; if(value === 0) return false; if (value ==="") return false; if (value === undefined) return false; if(value.isNaN) return false; return true; } function bouncer(arr) { arr = arr.filter(isFalsy); return arr; } console.log(bouncer([1, null, NaN, 2, undefined])); 

The reason is that if(value.isNaN) checks to see if a property called isNaN on value is truthy. The correct check is if (isNaN(value)) , because isNaN is a built-in function for testing for NaN (since NaN === NaN is false so you can't check that way):

 function isFalsy(value) { if(value === false) return false; if(value === null) return false; if(value === 0) return false; if (value ==="") return false; if (value === undefined) return false; if(isNaN(value)) return false; return true; } function bouncer(arr) { arr = arr.filter(isFalsy); return arr; } console.log(bouncer([1, null, NaN, 2, undefined])); 

That said, returning any falsy value from the filter callback will remove the entry, so you don't need your isFalsy at all (other than for learning purposes):

  arr = arr.filter(function(value) { return value; });

 function bouncer(arr) { arr = arr.filter(function(value) { return value; }); return arr; } console.log(bouncer([1, null, NaN, 2, undefined])); 

You don't have to use this whole, complicated function with a lot of conditions.

Just use .filter(v => v) , which will remove every falsy value.

v is an argument for the Array#filter function. We are filtering every truthy value and passing it to the res variable. Falsy values - [0, false, "", null, undefined, NaN] won't be filtered (passed).

 var arr = [1, null, NaN, 2, undefined, '', 0], res = arr.filter(v => v); console.log(res); 

You can simply use Array#filter()

 console.log(bouncer([1, null, NaN, 2, undefined])); function bouncer(arr){ return arr.filter(a=>a); } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM