简体   繁体   中英

How to return true if all values of array are true otherwise return false?

I have a array like this:

var arr = [ true, true, true ];

Now I want to get true , because all keys of array above are true .

another example:

var arr = [ true, false, true ];

Now I need to get false , because there is one false in the array.

How can I do that?

The shortest code to do this would be arr.every(x => x) or arr.every(function(x) {return x}) for ES5 compability.

The every method takes as an argument a function object that returns either true or false, which is used to test each element of the array.

I agree every is good answer but also you could use some and would be more faster if there are many elements in the array because this function will stop inmediately when first false is found. For example:

 var arr = [true, true, true, true, true, true ]; var allTrue = !arr.some(x => x === false); console.log(allTrue); var arr = [false, true, true, true, true, true ]; var notAllTrue = !arr.some(x => x === false); console.log(notAllTrue);

How about:

!arr.includes(false)

It's more readable and faster since it stops after the first false . See it in action:

 let arr = [ true, true, true ] console.log(!arr.includes(false)) arr = [ true, false, true ] console.log(!arr.includes(false))

I like to use the following trick also to solve the problem:

const arr = [ true, true, true ];
const allTrue = (arr.filter(Boolean).length == arr.length);
console.log(allTrue);

the expression in filter() will filter only true values and then we compare the length of the filtered array with the original array to check if all true or not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM