0

I have an array of objects, currently I loop throught them and test them one by one, but I try to make my code more concice and easy to follow. I wonder weather there is a way, with javascript or underscore, to test if at least one item in array returns true.

  for (var x = 0; x < user.apilog.length; x++) {
    //test the conversion
    if(conversions[i].conditional(user.apilog[x]) ){
      //run if true
      break;
    }
  }

2 Answers 2

1

If user.apilog is an array, then you can use Array.prototype.some():

var found = user.apilog.some(function (item, i) {
    return conversions[i].conditional(item);
});

n.b. underscore also provides a some method that works pretty much the same way, with the benefit that it should work on array-like objects as well as actual arrays:

var found = _.some(user.apilog, function (item, i) {
    return conversions[i].conditional(item);
});
Sign up to request clarification or add additional context in comments.

3 Comments

Wow! that is sweet! I don't need IE8 support and I bet this will have better perfomance than something like underscore!
I didn't know about this before but couldn't you he just create a function check(elem, index, arr) and then call user.apilog.some(check)? edit: assuming the function checked if true or false
@pbrianq Yes, defining the function separately would certainly work, too. I'm using an anonymous function here because it's just a one-line function and defining it as a separate function might be overkill.
0

With underscore.js you could simply use _.some(user.apilog)

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.