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) {
...
}
To check if all of the values in an array are equal to null , use the every() method to iterate over the array and compare each value to null , e.g. arr. every(value => value === null) . The every method will return true if all values in the array are equal to null . Copied!
To check if an array is empty or not, you can use the . length property. The length property sets or returns the number of elements in an array. By knowing the number of elements in the array, you can tell if it is empty or not.
With every , you are going to check every array position and check it to be zero: const arr = [0,0,0,0]; const isAllZero = arr. every(item => item === 0);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With