I'm trying to take a JavaScript array of strings, and return a boolean value based on all the elements in it. A logical &&
between non-empty strings should return true. I've found simple way to return a bool between two strings, using !!("String1" && "String2")
.
However, if I had these two strings in an array like var myArr = ["String1","String2"]
, how would I go about doing this?
I'm trying to take a JavaScript array of strings, and return a boolean value based on all the elements in it. A logical &&
between non-empty strings should return true. I've found simple way to return a bool between two strings, using !!("String1" && "String2")
.
However, if I had these two strings in an array like var myArr = ["String1","String2"]
, how would I go about doing this?
3 Answers
Reset to default 6You're looking for the array every
method bined with a Boolean
cast:
var myArr = ["String1","String2"]
myArr.every(Boolean) // true
In fact you could use an identify function, or String
as well, though to properly convey your intention better make it explicit:
myArr.every(function(str) { return str.length > 0; }) // true
Here's a nice solution using every
:
function isEmpty(strings){
return !strings.every(function(str){
return !!str;
});
}
Demo on JSFiddle
How about something like this?
function checkArr(arr) {
for (var i = 0, length = arr.length; i < length; i++) {
if (!arr[i]) return false;
}
return true;
}
checkArr(['a','b']); // true
checkArr(['a','']); // false
Or you could do it in a slightly hackish one liner:
return !arr.join(',').match(/(^$|^,|,,|,$)/);