1

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 3

6

You're looking for the array every method combined 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
Sign up to request clarification or add additional context in comments.

Comments

1

Here's a nice solution using every:

function isEmpty(strings){
    return !strings.every(function(str){
        return !!str;
    });
}

Demo on JSFiddle

Comments

0

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(/(^$|^,|,,|,$)/);

1 Comment

The one-liner is a bit too hackish, it'll fail on some strings that contain commata. If you must, better use a less common delimiter. Btw, test is suited better than match here.

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.