I have an array and I would like a simple non-loop test if that arrays contains ONLY null
values. Empty array also counts as having only null values.
I guess another way to describe the issue is to test if the array has at least one non-null value.
So:
Good: [ null, null, null ]
Good: []
Bad: [ null, 3, null ]
An object array is populated with null values when it's instantiated. Collections on the other hand are empty at the beginning, so there' nothing that can be "populated" in the first place - well, you could fill them with null values if you wanted, but what would be the point of that?
The array can be checked if it is empty by using the array. length property. This property returns the number of elements in the array. If the number is greater than 0, it evaluates to true.
isArray() function to check the type of array, which can be used with . length property to check empty array. This method helps to determine that the value you have passed in this function is array or not.
You can avoid using an explicit loop by using Array#every
:
var all_null = arr.every(function(v) { return v === null; });
but of course internally the engine will still iterate over the array. Iterating over the array explicitly might actually be faster. The important thing to do is break out of the loop once you encounter an element which is not null
(the method does that).
This method is not supported in every browser, see the link for a polyfill.
The easiest way I can think of is a simple:
Array.prototype.isNull = function (){
return this.join().replace(/,/g,'').length === 0;
};
[null, null, null].isNull(); // true
[null, 3, null].isNull(); // false
JS Fiddle demo.
This takes the array, joins the elements of that array together (without arguments join()
joins the array elements together with ,
characters) to return a string, replaces all the ,
characters in that string (using a regular expression) with empty strings and then tests if the length is equal to 0
. So:
[null, 3, null].isNull()
Joined together to give:
',3,'
Has all the commas replaced (using the g
flag after the regular expression), to give:
'3'
Tested to see if its length is equal to 0
, to give:
false
It's worth noting that there is the problem of, potentially, the ,
featuring in the checked arrays.
Also, Felix Kling's answer is somewhat faster.
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