admin管理员组

文章数量:1405535

let's say I have an array with n elements of boolean values.

var a = [true,false,true,true,false]

How do I do the OR product of the array.

SO that var result = (true || false || true || true || false) = true

let's say I have an array with n elements of boolean values.

var a = [true,false,true,true,false]

How do I do the OR product of the array.

SO that var result = (true || false || true || true || false) = true

Share Improve this question edited Nov 2, 2015 at 9:52 airnet asked Nov 2, 2015 at 9:50 airnetairnet 2,6936 gold badges33 silver badges37 bronze badges 0
Add a ment  | 

5 Answers 5

Reset to default 9

You can use some :

var result = a.some(function(value) {
    return value;
});

All these suggestions are far too plex. Just keep it simple. If you want OR then you just need to check if the array contains a single true value:

var result = a.indexOf(true) != -1;

Similarly, if you wanted AND you could just check if it doesn't contain false value, also if you want an empty array to result in false then check the length too:

var result = a.length > 0 && a.indexOf(false) == -1;

Here is a working example, that shows both OR and AND in action.

And here is a performance review of all the current answers, where you can see keeping it simple like this is much quicker than the other suggestions (well, Nina is close to mine as her answer is similar, but less readable IMO). Of course you can argue performance isn't going to be noticed with something like this, but still better to use the fastest method anyway.

Short in one mand.

!!~a.indexOf(true)

You may iterate over the array and find it.

var a = [false,false,false,false,false]
var result = a[0];
for(i=0;i<a.length;i++){
    result = result || a[i]
}
alert(result);

I hope this would help you

https://jsfiddle/0yhhvhu7/3/

From MDN

The Array.prototype.reduce() method applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value.

a.reduce(function(prev, curr) {
  return prev || curr;
});

本文标签: javascriptGetting boolean result of arrayStack Overflow