Home > Back-end >  How does one perform a logical AND on an array of booleans in javscript?
How does one perform a logical AND on an array of booleans in javscript?

Time:08-17

Scenario and Question

Say you have an array of booleans in javascript:

[true, false, true, true, false]

What's the best practice for performing a logical 'AND' operation on all of these values so that the above example would become:

false

In other words, what's the best practice for AND'ing all of these values together?


My solution

The best/cleanest way I thought of is using the reduce function like so:

const array1 = [true, false, true, true];

const initialValue = array1[0];
const array1And = array1.reduce(
  (previousValue, currentValue) => previousValue && currentValue,
  initialValue
);

console.log(array1And); //false

Is there a simpler way to achieve the same?

CodePudding user response:

You could use the .every for AND or the .some for OR

const array1 = [true, false, true, true];

const or = array1.some(Boolean);
const and = array1.every(Boolean);

console.log({ or, and });

  • Related