1

I am currently looking for a solution how to check a string array with only empty strings. Is there an efficient way to achive this behavior?

['', '', '', ''] // This should be true
['', null, null, ''] // This should be true
['a', '', '', ''] // This should be false
2
  • Maybe I just expressed myself a bit unfortunate. I just really wanted to have a clean solution without, maybe something that exists in javascript already without reimplementing it or adding an additional loop for the sake of clean code. Commented Nov 19, 2019 at 8:03
  • 2
    if you mean a user defined loop (eg for loop or loops made by using some,every,forEach, etc) you could do a join('') (internal loop) and check for empty string Commented Nov 19, 2019 at 8:05

3 Answers 3

6

You can use some function:

let arr = ['', '', '', ''];
arr.some(Boolean);

it will check if some elements not false value ('', 0, null, undefined, false), if all of them are false; it will return true.

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

Comments

5

You need a loop, preferably with a short circuit.

const check = array => !array.some(Boolean);

console.log(check(['', '', '', '']));     //  true
console.log(check(['', null, null, ''])); //  true
console.log(check(['a', '', '', '']));    // false

Comments

0

Thanks to all of you incl. Patrick Evans. I use the join('') method. This looks fairly clean to me.

let arr = ['', '', '', ''] // This should be true

console.log(Boolean(arr.join(''));

1 Comment

Join method will loop through all items; no matter what the element is, but some will break the loop and return value on first true element.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.