2

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.

curiousCat
  • 157
  • 3
  • 11

4 Answers4

5

Check your answer out here, you'll certainly get a more in-depth answer here: Check if all values in array are true, then return a true boolean statement (javascript)

let arr1 = ['true', 'false', 'true'],
    arr2 = ['true', 'true', 'true'];

let checker = arr => arr.every(v => v === 'true');

console.log(checker(arr1));
console.log(checker(arr2));
3

Check that .every value is 'true'.

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

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Thank You for your suggestion. This works perfectly fine for me in Chrome. But the arrow operator isn't supported in IE. Are you able to advise on this, please?. – curiousCat Jun 14 '21 at 12:16
  • https://stackoverflow.com/questions/40216015/why-doesnt-this-arrow-function-work-in-ie-11 Best approach for a professional project: use Babel to transpile your code to ES5 automatically, if needed – CertainPerformance Jun 14 '21 at 13:37
  • Thanks for your suggestion. Exactly what I was looking for. – curiousCat Jun 14 '21 at 23:59
1

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');
traktor
  • 17,588
  • 4
  • 32
  • 53
1

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
Goutham
  • 295
  • 1
  • 7