Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .filter(): exit before the end

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;
});
like image 390
fabio Avatar asked Jul 26 '17 15:07

fabio


People also ask

Does JS filter keep order?

Yes, the . filter() method returns a new array, without the filtered elements in the same order as initially. The order of the elements is one of the main feature of a array.

How do we filter out elements using jQuery?

jQuery filter() Method The filter() method returns elements that match a certain criteria. This method lets you specify a criteria. Elements that do not match the criteria are removed from the selection, and those that match will be returned.

What is the use of jQuery each () function?

each(), which is used to iterate, exclusively, over a jQuery object. The $. each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time.

What will the filter method return?

The filter() method is a copying method. It does not alter this but instead returns a shallow copy that contains the same elements as the ones from the original array (with some filtered out).


1 Answers

You can't break out of a filter() loop as it's designed to apply its logic to all elements.

If you want to exit a loop early, I'd suggest changing your logic to use each(). Then you can return false; to exit the loop:

var target_number = 3, matches = [];

$('#my_id image').each(function(i, el) {
  if (el.attributes.x.value == x) {
    matches.push($(this));

    if (matches.length == target_number)
      return false;
  }
});

matches will now be roughly equivalent to the content of your image_match variable, except it will be an array instead of a jQuery object.

Alternatively you can use map() to directly build an array which contains only the values required:

let matches = $('#my_id image').map((i, el) => el.attributes.x.value === x ? $(el) : null).get();
like image 138
Rory McCrossan Avatar answered Oct 18 '22 18:10

Rory McCrossan