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条回答
Deceive 欺骗
2楼-- · 2020-01-27 03:03
function bouncer(arr) {

// Don't show a false ID to this bouncer.

for (var i = 0; i < arr.length; i++) {
        if (!arr[i]) {
            arr.splice(i, 1);
            i = i-1;
        }
    }
    return arr;

}

bouncer([7, "ate", "", false, 9]);
查看更多
▲ chillily
3楼-- · 2020-01-27 03:06

You use isNaN() in wrong way. It should be something like following:

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

}

Also you can rewrite it:

function bouncer( arr ){
    return arr.filter( function( value ){
        return value;
    });
}
查看更多
Bombasti
4楼-- · 2020-01-27 03:06

Just negate twice to "cast" to boolean. !NaN === true => !!NaN === false

    const truthy = arr.filter(o => !!o)
查看更多
够拽才男人
5楼-- · 2020-01-27 03:08
truthyArray = arr.filter(el => el)

^ that's how you do it

查看更多
Summer. ? 凉城
6楼-- · 2020-01-27 03:08
function bouncer(arr) {  
  var result = []; 
   for (var i = 0; i < arr.length; i++) {
     if (arr[i]) {
      result.push(arr[i]);
     }
   }
  return result;
 }

 bouncer([7, "ate", "", false, 9]);
查看更多
老娘就宠你
7楼-- · 2020-01-27 03:09
myArray = [false, null, 0, NaN, undefined, ""];
myArray.map(item => {
//if you want you can write logic
        console.log(item);
    })
    // Get rid of bad values
    .filter(Boolean);

it will return [].

查看更多
登录 后发表回答