Boolean algebra in javascript

Is it possible to use Boolean algebra in JS?

For example, I would like to skip an array containing true and false, and simplify it to only true or false.

Doing this with Boolean algebra seems like an elegant way to do it ...

[true,true,true,true] //would like to do a comparison that lets me //simply add the previous value to the current iteration of a loop // and have this return true [false,true,true,true]//this on the other hand should return false 
+4
source share
5 answers

I think a simple solution would be

 return array.indexOf(false) == -1 
+19
source

Try Array.reduce :

 [false,true,true,true].reduce(function(a,b) { return a && b; }) // false [true,true,true,true].reduce(function(a,b) { return a && b; }) // true 
+15
source

Do you mean:

 function all(array) { for (var i = 0; i < array.length; i += 1) if (!array[i]) return false; return true; } 

Or is there something more complex that you are looking for?

+5
source
 function boolAlg(bools) { var result = true; for (var i = 0, len = bools.length; i < len; i++) { result = result && bools[i] } return result; } 

Or you can use this form, which is faster:

 function boolAlg(bools) { return !bools[0] ? false : !bools.length ? true : boolAlg(bools.slice(1)); } 
+1
source
 for(var i=0; i < array.length;++i) { if(array[i] == false) return false; } return true; 
0
source

All Articles