9

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

2
  • 2
    Instead of moving backwards through the array of $as (decrementing towards 0) and then reversing the array, why not go forwards through the array of $as, by incrementing towards i<$lis.length? Commented Jan 2, 2012 at 16:03
  • 1
    Where did you call links.reverse().push(youtubeid($as[i].href));? In your for loop? You should just call reverse once. Commented Jan 2, 2012 at 16:06

3 Answers 3

14

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This also works. What is the best solution Jason's or yours ? And do you know how to skip the first one in the array ? Thanks
@ceasar to remove the first element - var first = links.shift();
2

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));
    }

2 Comments

He jason. That works :-) Now how can I remove only the first one in the array Thanks for your help
links.shift(); is the answer to my own question :-)
0

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.