Hi I have an array like: [null,null,null,null] in javascript. How can I know if the array has all values equal to null without iterating over it?
There is no way to check for all null values, you would have to iterate over it, or the function you call will have to in the background. However, if you want, you could use the native Array method filter to help you out.
var allNull = !arr.filter(Boolean).length;
This will work with any falsy value, like undefined, zero, NaN, or an empty string. A more precise form is
var allNull = !arr.filter(function(elem){ return elem !== null; }).length;
Which would check for only null.
Another possibility is using .join:
var allNull = !arr.join("").length;
This checks for null, undefined, or ""
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