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 bee:
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?
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 bee:
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?
Share Improve this question asked Aug 17, 2022 at 14:28 ParmParm 5781 gold badge7 silver badges21 bronze badges 1-
4
Array.every()
: developer.mozilla/en-US/docs/Web/JavaScript/Reference/… ? – Matt Morgan Commented Aug 17, 2022 at 14:30
1 Answer
Reset to default 9You 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 });