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
5 Answers
Reset to default 9You 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
版权声明:本文标题:javascript - Getting boolean result of array - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744239061a2596697.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论