Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort Array by String

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');
like image 321
Howdy_McGee Avatar asked Dec 04 '22 17:12

Howdy_McGee


2 Answers

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.

like image 140
Andreas Wong Avatar answered Dec 21 '22 23:12

Andreas Wong


use the built-in array functions:

streams.sort().reverse();

That was easy...

MDN docs:

  • reverse
  • sort
like image 29
gdoron is supporting Monica Avatar answered Dec 21 '22 23:12

gdoron is supporting Monica