Remove all falsy values from an array

2020-01-27 03:03发布

I would like to remove all falsy values from an array. Falsy values in JavaScript are false, null, 0, "", undefined, and NaN.

function bouncer(arr) {
 arr = arr.filter(function (n) { 
    return (n !== undefined && n !== null && n !== false && n !== 0 && n !== "" && isNaN()!=NaN); });
  return arr;
}

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

The above is getting satisfied for all except the NaN test case. Can someone help me check in the array whether it contains NaN or not?

22条回答
祖国的老花朵
2楼-- · 2020-01-27 03:23

bouncer function:

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

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

查看更多
够拽才男人
3楼-- · 2020-01-27 03:25

Using filter we can write

function bouncer(arr) {
 return arr.filter(item => item);
}
bouncer([false, null, 0, NaN, undefined, ""]) // will return [].
查看更多
Root(大扎)
4楼-- · 2020-01-27 03:26
function removeFalsy(value){

  var val = Boolean(value);
  if(!val)
    return false;
  return true;
}

function bouncer(arr) {

  return arr.filter(removeFalsy);
}

bouncer([7, "ate", "", false, 9]);
查看更多
虎瘦雄心在
5楼-- · 2020-01-27 03:30

Thanks for all working answers above. Here are 3 approaches to solve the problem. Third solution addressed problem by your approach @Vignesh.

1. 
function bouncer(arr) {
  return arr.filter( function( val ){
        return val;
    });
}

2. 
function bouncer(arr) {
return arr.filter(Boolean);
}
3.
  function bouncer(arr) {
  return arr.filter(function(val){
      return val !== false && val !== "" && !(Number.isNaN(val)) && val !== 
undefined && val !== 0 && val !== null;
    });
 }
查看更多
登录 后发表回答