Calvin
Calvin

Reputation: 197

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("", "", "", "")

Upvotes: 3

Views: 320

Answers (2)

guyaloni
guyaloni

Reputation: 5862

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.

Upvotes: 4

RobG
RobG

Reputation: 147343

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)});    

Upvotes: 1

Related Questions