Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking Array Emptiness with Javascript

Is there a way to determine the following JavaScript array is empty without manually iterating through it?

var js_array = Array("", "", "", "")
like image 589
Calvin Avatar asked Nov 17 '25 08:11

Calvin


2 Answers

I guess you want to check whether array contains some non-empty strings.

Use filter to remove empty strings:

var tmp_js_array = js_array.filter(Boolean)

(see filter documentation)

Then you can check whatever you want - in your case tmp_js_array will be empty.

like image 59
guyaloni Avatar answered Nov 18 '25 21:11

guyaloni


There is Array.protoype.every, which can be used to test whether every value meets a test and returns false for the first that doesn't. So if your definition of "empty" is that all members are empty strings, then:

['','','',''].every(function(v){return !/\S/.test(v)}); // true

will return true if every member does not contain any non–whitespace characters. Alternatively, you can use some to see if any member contains a non–whitespace character and negate the result:

!['','','',''].some(function(v){return /\S/.test(v)});    
like image 41
RobG Avatar answered Nov 18 '25 21:11

RobG