Becky Becky - 7 months ago 21
Javascript Question

create array in reverse order

I've got buttons with a common class (

buttons
). How can I add their
ID
s in to an array in a reverse order?

var yourArray = [];
$('.buttons').each(function() {
yourArray.push( $(this).prop('id') );
});

Answer

You could create the array by adding each element to the beginning of the array using unshift():

var yourArray = [];
$('.buttons').each(function() {
     yourArray.unshift(this.id);
});

Alternatively you can create it in the current order and then reverse() it. Also note that you can use map() to create the array initially:

var yourArray = $('.buttons').map(function() {
    return this.id;
}).get().reverse();

Finally you can use this.id instead of creating a jQuery object just to access a property already accessible without the need of object creation.

Comments