Reputation: 15006
I have an array that looks like this simplified:
[{one: false,two: 'cat'},{one: true, two: 'dog'},{one: false, two: 'ball'}]
I want to check if any of the one, values are true. The solution I can think of is something like
var truthness;
array.forEach(function (element, i, array) {
if(element.one){
truthness = true
break;
}
}
if(truthness){
//code
}else{
//other code
}
is there a better way to do this?
Upvotes: 3
Views: 4829
Reputation: 63524
The same as you are doing but maybe a little neater (YMMV), you could use some
to check if any of the values are true. The beauty of some
is:
If such an element is found, some immediately returns true.
If you're catering for older browsers there's a polyfill at the bottom of that page.
var data = [{one: false,two: 'cat'},{one: true, two: 'dog'},{one: false, two: 'ball'}];
var data2 = [{one: false,two: 'cat'},{one: false, two: 'dog'},{one: false, two: 'ball'}];
function oneIsTrue(data) {
return data.some(function (el) {
return el.one;
});
}
oneIsTrue(data); // true
oneIsTrue(data2); // false
Upvotes: 0
Reputation: 1127
You could also use Array.some
:
var arr = [{one: false,two: 'cat'},{one: true, two: 'dog'},{one: false, two: 'ball'}];
var truth = arr.some(function(elem) {
return elem.one;
});
From MDN:
some
executes the callback function once for each element present in the array until it finds one where callback returns a true value. If such an element is found, some immediately returns true. Otherwise, some returns false. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values.
Upvotes: 0
Reputation: 816282
Arrays have a method .some
, which returns true
if the callback returns true
for any element in the array, or false
if it returns false
for every element in the array.
var truthness = array.some(function(element) {
return element.one;
});
Upvotes: 9
Reputation: 3763
What you are doing would work perfectly one small optimization might be to use a while loop.
var i = array.length;
while (i--)
if (array[i].one)
break;
if (i >= 0) {
//truhness
} else {
//other code
}
it basically does what you did just with possibly a little faster loop.
Upvotes: 0