5

Is there any way to use boolean algebra in JS?

Eg I would like to loop through an array containing true & false, and simplify it down to either only true, or false.

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

would like to do a comparison that lets me simply add the previous value to the current iteration of a loop

[true, true, true, true] // return true

[false, true, true, true] // return false
1
  • Do you mean 'and-ing' them all together? Commented Jul 14, 2011 at 18:04

6 Answers 6

21

I think a simple solution would be

return array.indexOf(false) == -1
Sign up to request clarification or add additional context in comments.

2 Comments

This won't work in ie7 or less, unless you define the indexOf function manually
This looks faster, but later on it could become a little harder to understand what is doing here.
17

Try Array.reduce:

[false,true,true,true].reduce((a,b) => a && b)  // false

[true,true,true,true].reduce((a,b) => a && b) // true

Comments

7

You mean like:

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 you're looking for?

1 Comment

+1 because it's simple, could easily be converted to handle a requirement of logical OR instead of AND, and it's essentially the same as the accepted answer that uses .indexOf() except it will work in all browsers.
2
function boolAlg(bools) {    
    var result = true;

    for (var i = 0, len = bools.length; i < len; i++) {
        result = result && bools[i]

    }

    return result;
}

Or you could use this form, which is faster:

function boolAlg(bools) {    
    return !bools[0] ? false :
        !bools.length ? true : boolAlg(bools.slice(1));
}

Comments

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

Comments

1

ES6 Array.prototype.every:

console.log([true, true, true, true].every(Boolean));
console.log([false, true, true, true].every(Boolean));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.