48

I have an array of booleans, which begins as false, because at least one of the values is false: var validation = [false, true, true] In certain moment, it'll have all the options(index) as "true", like: validation = [true, true, true] How can I set this array as "true" when all the options are true?

Sorry for the silly question.

jeanm
  • 672
  • 1
  • 6
  • 19
  • You could also use "some" for example: var arr = [true, true, true, true, true, true ]; var allTrue = !arr.some(x => x === false); console.log(allTrue); – darmis Dec 22 '18 at 17:49
  • @darmis moreover `some` will be faster as it will stop as soon as it finds `false` - no need to check every item to see if they all `true` – godblessstrawberry Jul 08 '21 at 09:50

3 Answers3

114

You can use .every() method:

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

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

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

As mentioned by @Pointy, you can simply pass Boolean as callback to every():

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

let checker = arr => arr.every(Boolean);

console.log(checker(arr1));
console.log(checker(arr2));
Mohammad Usman
  • 34,173
  • 19
  • 88
  • 85
  • 13
    Or simply `let result = arr1.every(Boolean);` - the Boolean constructor will return `true` or `false`. – Pointy Dec 22 '18 at 17:08
23

You can use this to check if every values in array is true,

validation.every(Boolean)
Sandeepa
  • 3,052
  • 5
  • 22
  • 38
6

You can check if array have "false" value using "includes" method, for example:

if (validation.includes(value)) {
    // ... your code
}
Andellys
  • 675
  • 3
  • 7