jQuery .filter(): exit before the end

Viewed 4092

I have this code:

var image_match = $('#my_id image').filter(function(i, el) {
    return  el.attributes.x.value == x_image;
});

$('#my_id image') gives a very long array (some thousands) but luckily I know how many elements will pass the test (generally just one) so I could stop the 'loop' as soon as it finds the element(s). The problem is I don't know how to do (or if it's possible).

This is to increase the efficiency, so I'm looking for an efficient solution.

Maybe something like this, but is it efficient?

var target_number=3;//or whatever
var image_match = $('#my_id image').filter(function(i, el) {
    var counter=0;
    if (el.attributes.x.value == x_image) {
        counter+=1;
    };
    if (counter==target_number) {
        return  el.attributes.x.value == x_image;
        break;//return (false);//exit
    }
    return  el.attributes.x.value == x_image;
});
1 Answers
Related