Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery $.each() reverse/backward iteration

Tags:

jquery

each

I'm parsing an array using $.each(), but inside it, I'm using .splice() method, so I need to iterate backward. Is it possible ?

var store = [...];
//...
var rules = [...];
//...
$.each(store, function(index, element) { // This loop needs to iterate backward
    $.each(rules, function(index2, rule) {
        if (element.id == rule.id) {
            store.splice(index, 1);
        }
    });
});

WARN :

  • I don't want to reverse the array, it wouldn't be the same behavior.
  • Also I know I could use for, I just want to know if it's achievable using $.each
like image 553
Elfayer Avatar asked Jul 24 '14 10:07

Elfayer


People also ask

How to iterate backwards with jQuery each function?

You cannot iterate backwards with the jQuery each function, but you can still leverage jQuery syntax. //get an array of the matching DOM elements var liItems = $ ("ul#myUL li").get (); //iterate through this array in reverse order for (var i = liItems.length - 1; i >= 0; --i) { //do Something }

How can I reverse an array in jQuery?

I found Array.prototype.reverse unsuccessful with objects, so I made a new jQuery function to use as an alternative: jQuery.eachBack (). It iterates through as the normal jQuery.each () would, and stores each key into an array. It then reverses that array and performs the callback on the original array/object in the order of the reversed keys.

How do I iterate over a non-jQuery object?

Iterating over jQuery and non-jQuery Objects. jQuery provides an object iterator utility called $.each() as well as a jQuery collection iterator: .each(). These are not interchangeable. In addition, there are a couple of helpful methods called $.map() and .map() that can shortcut one of our common iteration use cases.

How do I iterate over an array in jQuery?

The $.each() function is not the same as $(selector).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.


1 Answers

$.each(store.reverse(), function(index, element) { // This loop iterate backward
[...]

This works, it's the same as this post jquery-each-backwards. But the point here is, you're applying this over the store.

like image 168
Kadaiser Avatar answered Oct 12 '22 13:10

Kadaiser