How to return a boolean true if all the values in an array are true (strings) and if one of the value is false(string) stop checking using Javascript

Viewed 2614

I have an array

var myarr = ["true","false","true"];

I want the above to return false of boolean type.

var myarr = ["true","true","true"];

I want the above to return true of boolean type. Can someone please help with what's the most efficient way to achieve this?.

Is it best to first convert the string to boolean in another array and then use .every()?.

Please advise. Thank You.

4 Answers

Check that .every value is 'true'.

return myarr.every(val => val === 'true');

To stop processing if a "false" string is encountered, use Array.prototype.some

const allTrue = arr => !arr.some(entry => entry === 'false');

console.log("expect false true:");
console.log( allTrue(["true","false","true"]) );
console.log( allTrue(["true","true","true"]) );

If you need to check for 'true' strings, use a !== operator in the some argument:

const allTrue = arr => !arr.some(entry => entry !== 'true');

You can use like below, because Array.every iterates every element present in an array even it has false present in it.

const result = myarr.includes('false'); // true

const result2 = myarr.some((v) => v === 'false'); //  true
Related