Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How does one perform a logical AND on an array of booleans in javscript?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel


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?

>Solution :

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 });
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading