3

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

var js_array = Array("", "", "", "")
5
  • 5
    The array is not empty: it contains four elements. Commented Dec 30, 2015 at 21:14
  • 1
    I suppose you could test if js_array.join('') is true or false, but that leaves open a bunch of false positives. The fact is, that array isn't "empty", and you have to define exactly what you want to test for first. Commented Dec 30, 2015 at 21:14
  • You could filter and only return elements that are truthy then check the length of the array. Commented Dec 30, 2015 at 21:15
  • Array("", "", "", "").every(String) Commented Dec 30, 2015 at 21:30
  • @dandavis—probably better to use Boolean to make the type conversion explicit (thought it's one more character to type). Commented Jan 2, 2016 at 10:10

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

That doesn't actually check whether the array contains non–empty strings, it just removes members where ToBoolean returns false. At least a further check is required to see if the new array is the same length as the old.
You are right, since I don't know exactly what @Calvin wants to check I left this for him... (tmp_js_array.length == 0 will do the work for example)
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.