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:18
function bouncer(arr) {

    function filterFalse(value) {
        var a = Boolean(value);
        if (a === true) {
            return a;
        }
        return a;
    }

    function filterArray(x) {
        var y = filterFalse(x);
        if (y) {
            return true;
        } else {
            return false;
        }
    }

    var newArr = arr.filter(filterArray);
    return newArr;
}

bouncer([1, null, NaN, 2, undefined]);
查看更多
Bombasti
3楼-- · 2020-01-27 03:18

Try using filter and Boolean:

let array = [7,"ate","",false,9];
array.filter((values) => {return Boolean(values) === true })
查看更多
何必那么认真
4楼-- · 2020-01-27 03:20

You can use Boolean :

var myFilterArray = myArray.filter(Boolean);
查看更多
▲ chillily
5楼-- · 2020-01-27 03:21

This is another equivalent, but illustrative, solution:

function bouncer( arr ){
    return arr.filter( function( value ){
        return value ? true : false;
    });
}

This code sample is illustrative because it indicates to a reader that the variable value will be evaluated as truthy or falsey, and the anonymous function will return a boolean, either true or false, mapping to the evaluation of value.

For someone who is not familiar with this approach of removing values from an array based on their truthiness, or for someone who is not familiar with (or has not read the documentation on) the filter function, this example is the most concise that still conveys the behavior of the filter function.

Of course, in your application you may opt for the more concise, yet less insightful, implementation:

function bouncer( arr ){
    return arr.filter( function( value ){
        return value;
    });
}
查看更多
萌系小妹纸
6楼-- · 2020-01-27 03:21
function falsy(value) {
      if (value) {
        return value;
      }
    }

    function bouncer(arr) {
      var filter = arr.filter(falsy);
      return filter;
    }

    bouncer([7, "ate", "", false, 9]);
查看更多
成全新的幸福
7楼-- · 2020-01-27 03:21

lodash can do the trick nicely, there is a _.compact() function.

const arr = [7, "ate", "", false, 9, NaN];
console.log(_.compact(arr));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

查看更多
登录 后发表回答