JavaScript/jQuery equivalent of LINQ Any()

dilbert picture dilbert · May 10, 2011 · Viewed 22.7k times · Source

Is there an equivalent of IEnumerable.Any(Predicate<T>) in JavaScript or jQuery?

I am validating a list of items, and want to break early if error is detected. I could do it using $.each, but I need to use an external flag to see if the item was actually found:

var found = false;
$.each(array, function(i) {
    if (notValid(array[i])) {
        found = true;
    }
    return !found;
});

What would be a better way? I don't like using plain for with JavaScript arrays because it iterates over all of its members, not just values.

Answer

Sean Vieira picture Sean Vieira · May 2, 2014

These days you could actually use Array.prototype.some (specced in ES5) to get the same effect:

array.some(function(item) {
    return notValid(item);
});