Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript array null check without iterating

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?

like image 739
Aditya Kappagantula Avatar asked Mar 01 '26 01:03

Aditya Kappagantula


1 Answers

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 ""

like image 78
PitaJ Avatar answered Mar 03 '26 15:03

PitaJ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!