ceasar
ceasar

Reputation: 1522

jquery reverse array

I have the following snippet which returns some youtube id's. Now I want to reverse the output (because now it is the last first)

if (options.slideshow) {
var links = [];
var $lis = holder.parents('#yt_holder').find('li');
var $as = $lis.children('a');
for(var count = $lis.length-1, i = count; i >= 0; i--){
    links.push(youtubeid($as[i].href));
    }
 slideshow = '&playlist=' + links + '';
 alert(slideshow);
}

I tried .reverse() but some items seems to be missing then

links.reverse().push(youtubeid($as[i].href));

Any help will be appreciated. Ceasar

Upvotes: 9

Views: 32505

Answers (3)

Aakash Dhoundiyal
Aakash Dhoundiyal

Reputation: 3

Hi you after reversing the links array ,you have to assign it to other array and hence it will work.

var slideshow = [];
slideshow = links.reverse();

Upvotes: 0

Alnitak
Alnitak

Reputation: 339786

You should reverse the list after you've accumulated it:

for ( ... ) {
    ...
}
links = links.reverse();

but it would be better to just put the elements into the array in the right order in the first place.

Upvotes: 14

Jason Gennaro
Jason Gennaro

Reputation: 34855

Try adding the videos in the reverse order, so instead of this

for(var count = $lis.length-1, i = count; i >= 0; i--){
    links.push(youtubeid($as[i].href));
    }

Do this

for(var i = 0, count = $lis.length; i < count; i++){
    links.push(youtubeid($as[i].href));
    }

Upvotes: 2

Related Questions