96

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.

2
  • 2
    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); Commented Dec 22, 2018 at 17:49
  • 1
    @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 Commented Jul 8, 2021 at 9:50

3 Answers 3

202

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));

Sign up to request clarification or add additional context in comments.

3 Comments

Or simply let result = arr1.every(Boolean); - the Boolean constructor will return true or false.
Boolean means that it cast each array member into Boolean value right?
@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.
41

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

validation.every(Boolean)

3 Comments

This would fail if it includes strings ["FALSE"].every(Boolean) would return true
@TOLULOPEADETULA That is expected. "FALSE" is a truthy value in JS. You cannot evaluate string values to false based on their content
Boolean means that it cast each array member into Boolean value right?
13

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

if (validation.includes(value)) {
    // ... your code
}

3 Comments

no this doesn't do justice for all values, it only check if one of the array value includes your value!
@Danish if (!validation.includes(false)) { } for example. Although .every() is much better!!
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 :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.