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');
streams.sort()
Would give you ["offline", "offline", "offline", "offline", "online", "online", "online", "online"]
since f comes 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With