Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if array has only null values in it [closed]

Tags:

javascript

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 ]
like image 206
Discipol Avatar asked Oct 12 '13 18:10

Discipol


People also ask

Is array filled with 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?

How do you check if a slot in an array is empty?

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.

How check array is null or not in Javascript?

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.


2 Answers

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.

like image 65
Felix Kling Avatar answered Oct 05 '22 05:10

Felix Kling


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.

like image 31
David Thomas Avatar answered Oct 05 '22 04:10

David Thomas