79

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
  • 1,083
  • 1
  • 9
  • 22
  • 1
    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

177

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
  • 37,952
  • 20
  • 92
  • 95
  • 20
    Or simply `let result = arr1.every(Boolean);` - the Boolean constructor will return `true` or `false`. – Pointy Dec 22 '18 at 17:08
  • `Boolean` means that it cast each array member into Boolean value right? – buncis May 13 '23 at 10:51
  • @buncis in short yes. `Boolean` is a built in function available that will cast its argument to corresponding boolean value when used without `new` operator. – Mohammad Usman May 15 '23 at 04:30
32

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

validation.every(Boolean)
Sandeepa
  • 3,457
  • 5
  • 25
  • 41
11

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

if (validation.includes(value)) {
    // ... your code
}
Anlis
  • 769
  • 3
  • 9
  • no this doesn't do justice for all values, it only check if one of the array value includes your value! – Danish Oct 24 '22 at 17:55
  • 1
    @Danish if (!validation.includes(false)) { } for example. Although .every() is much better!! – Jamie G Dec 14 '22 at 22:11
  • `includes` is definitely better because I believe `every` is ES6 and above, or just a very new feature. I don't use `includes` as often as `indexOf`, so I'll use that :) – RixTheTyrunt Jun 21 '23 at 14:16