Alex
Alex

Reputation: 5724

Boolean algebra in javascript

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

Upvotes: 5

Views: 4490

Answers (6)

digitalbath
digitalbath

Reputation: 7354

Try Array.reduce:

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

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

Upvotes: 17

tenshi
tenshi

Reputation: 26404

ES6 Array.prototype.every:

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

Upvotes: 1

Adam
Adam

Reputation: 12690

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));
}

Upvotes: 2

Lourens
Lourens

Reputation: 1518

I think a simple solution would be

return array.indexOf(false) == -1

Upvotes: 21

uadnal
uadnal

Reputation: 11445

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

Upvotes: 1

David Wolever
David Wolever

Reputation: 154682

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?

Upvotes: 7

Related Questions