Right now, I have a list of streams, and I want to push streams with the string "online" to the front of the array, but I want to do this very quickly. I know I can just duplicate the array value by value and push the online values to the front, but I was wondering if there is a better way to do this.
This is just some sample code but it is similar to what I have going. How can I just rearrange my array to push online toward the front? I'm open to JavaScript or jQuery answers.
var streams = new Array('online', 'offline', 'online', 'offline', 'online', 'offline', 'offline', 'online');
Right now, I have a list of streams, and I want to push streams with the string "online" to the front of the array, but I want to do this very quickly. I know I can just duplicate the array value by value and push the online values to the front, but I was wondering if there is a better way to do this.
This is just some sample code but it is similar to what I have going. How can I just rearrange my array to push online toward the front? I'm open to JavaScript or jQuery answers.
var streams = new Array('online', 'offline', 'online', 'offline', 'online', 'offline', 'offline', 'online');
Share
Improve this question
edited Apr 9, 2012 at 2:55
gengkev
1,9592 gold badges21 silver badges31 bronze badges
asked Apr 9, 2012 at 2:46
Howdy_McGeeHowdy_McGee
10.7k30 gold badges115 silver badges190 bronze badges
3 Answers
Reset to default 11streams.sort()
Would give you ["offline", "offline", "offline", "offline", "online", "online", "online", "online"]
since f es before n in off and online
You can use .reverse()
to reverse the order of elements.
streams.sort().reverse()
Should be what you are looking for, you don't need to reassign the array (i.e. doing streams = streams.sort().reverse()
) as it does the operations internally within your array.
use the built-in array functions:
streams.sort().reverse();
That was easy...
MDN docs:
reverse
sort
streams.sort();
Otherwise you probably just want to loop through the array.