最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Sort Array by String - Stack Overflow

programmeradmin5浏览0评论

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
Add a ment  | 

3 Answers 3

Reset to default 11
streams.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.

发布评论

评论列表(0)

  1. 暂无评论