Check if all values in array are true, then return a true boolean statement (javascript)

Viewed 93780

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.

3 Answers

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

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

validation.every(Boolean)

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

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