Detect if an array has only null values

I have an array, and I need a simple test without a loop if these arrays contain ONLY null values. An empty array also considers that it has only null values.

I guess another way to describe the problem is to check if the array has at least one nonzero value.

So:

 Good: [ null, null, null ] Good: [] Bad: [ null, 3, null ] 
+6
source share
3 answers

The easiest way I can think of is 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 an array, concatenates the elements of this array together (without join() arguments join() elements of the array along with the characters , ) to return a string, replaces all the characters in this string (using a regular expression) with empty strings, and then checks to see if length 0 . So:

 [null, 3, null].isNull() 

Joined to give:

 ',3,' 

All commas are replaced (using the g flag after the regular expression) to give:

 '3' 

Tested if its length is 0 to give:

 false 

It is worth noting that there is a problem, possibly in , in proven arrays.

In addition, Felix Kling's answer is somewhat faster .

+17
source

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. Array iteration can obviously be faster. The important thing to do is to exit the loop as soon as you come across an element that is not null (the method does this).

This method is not supported in every browser, see the link for polyfill.

+15
source
 var arrayData1 = [null, null, null]; var arrayData2 = []; var arrayData3 = [null, 3, null]; var arrayData4 = [3]; function isNull(inputArray) { if (inputArray.length) { var currentElement = inputArray[0]; for (var i = 1, len = inputArray.length; i < len && currentElement === null; i += 1) { currentElement = currentElement || inputArray[i]; } if (currentElement !== null) { return false; } } return true; } console.log(isNull(arrayData1)); console.log(isNull(arrayData2)); console.log(isNull(arrayData3)); console.log(isNull(arrayData4)); 

Output

 true true false false 

Edit 1: And here is the most effective solution (suggested by user 2736012). This decision applies the KISS principle. K eep I t S imple, S illy.

 function isNull(inputArray) { for (var i = 0, len = inputArray.length; i < len; i += 1) if (inputArray[i] !== null) return false; return true; } 

The result of the work: http://jsperf.com/so-q-19337761/6

+4
source

Source: https://habr.com/ru/post/955847/


All Articles