How do I check if all elements of an array are null?

前端 未结 3 471
生来不讨喜
生来不讨喜 2020-12-18 09:46

What\'s the best way to check for an array with all null values besides using Lodash, possibly with ES6?

var emp = [null, null, null];
if (_.compact(emp).len         


        
相关标签:
3条回答
  • 2020-12-18 09:48

    A side note: Your solution doesn't actually check for an all-null array. It just checks for an all-falsey array. [0, false, ''] would still pass the check.

    You could use the Array#every method to check that every element of an array meets a certain condition:

    const arr = [null, null, null];
    console.log(arr.every(element => element === null));

    every takes a callback in which the first argument is the current element being iterated over. The callback returns true if the element is null, and false if it is not. If, for all the elements, the callback returns true, it will evaluate to true, thus if all elements in the array are null, it's true.

    0 讨论(0)
  • 2020-12-18 09:48

    You can use Array#every or lodash's _.every() with _.isNull():

    var emp = [null, null, null];
    
    var result = emp.every(_.isNull);
    
    console.log(result);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

    0 讨论(0)
  • 2020-12-18 09:58

    Another way to solve this. Is join the array elements and replace the left out ',' with empty space.

    var emp = [null, null, null];
    
    if(emp.join(',').replace(/,/g, '').length === 0) {
     console.log('null');
    }

    0 讨论(0)
提交回复
热议问题