Reputation: 430
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).length == 0) {
...
}
Upvotes: 18
Views: 35886
Reputation: 191916
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>
Upvotes: 2
Reputation: 57924
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.
Upvotes: 39
Reputation: 12176
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');
}
Upvotes: 1