3

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?

3
  • Not really, you'd have to iterate either way. Commented Mar 19, 2014 at 17:12
  • Libraries like jQuery and Underscore.js have functions for this, but if you're not using them then this is the way to do it. Commented Mar 19, 2014 at 17:12
  • 1
    Here's a neater way to write it -> jsfiddle.net/LS9kH Commented Mar 19, 2014 at 17:15

4 Answers 4

10

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;
});
Sign up to request clarification or add additional context in comments.

1 Comment

I like that much better than my solution.
0

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.

Comments

0

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.

Comments

0

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

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.