Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse $.each output in jQuery

I'm making a little secret tool. The output will be in a table, and on the left-hand side I'd like to list the numbers I have stored in $.each(). So here's my code:

$.each([1,2,3,4,5], function(i, l){


   var lol = (some math stuff here);

   $("#output").append("<tr><td>" + l + "</td><td>" + lol + "</td><tr>");

});

What this does is output the following:

1.  lol1
2.  lol2
3.  lol3
4.  lol4
5.  lol5

What I'm trying to do is reverse that l value but leave everything else alone so that the output instead looks like this:

5. lol1
4. lol2
3. lol3
2. lol4
1. lol5
like image 377
ggwicz Avatar asked Dec 06 '22 17:12

ggwicz


2 Answers

Create a copy of the array and then reverse that one. Here's a working example: http://jsfiddle.net/naRKF/

And the code (the HTML isn't the same as yours, but the JS technique is what you should focus on/use):

var arr1 = [1,2,3,4,5];
var arr2 = arr1.slice().reverse(); //creates a copy and reverses it

var html = '';
for(var i = 0; i < arr1.length; i++){
    html += '<div>' + arr2[i] + '.' + ' lol' + arr1[i] + '</div>';
}

$('body').append(html);
like image 169
maxedison Avatar answered Dec 10 '22 12:12

maxedison


$.each() will always iterate the array in the correct order. You want to use a for loop for this one, rather then jQuery's $.each().

like image 28
Madara's Ghost Avatar answered Dec 10 '22 13:12

Madara's Ghost