JS 陣列排序範例

馬老師離開待了約十幾年的教學界,目前在外商科技公司擔任Senior Consultant的工作,原因當然很多,未來有空再慢慢發文章分享,剛好最近有點時間,怕以後忘記,把最近專案中用到的一些程式筆記下來,如果大家有需要,也可以參考使用,這一篇是關於Javascript陣列排序的部分。

通常若有較多的內容需要儲存,變數就沒有陣列來的好用,所以陣列是拿來儲存大量的資料時所使用的,且儲存在裡面的資料,還可以選擇經過排序之後再呈現至畫面上,例如:

var name = ["stanley", "jack", "anita" , "mary"];

name.sort() //依照字母排序
console.log(name); // 輸出 ["anita", "jack", "mary", "stanley"]

names.reverse() //反轉陣列內容
console.log(name); //輸出 ["stanley", "mary", "jack", "anita"]

但若我們同時有多個陣列,但希望以其中之一的內容排序時,也可以同步更新到另外一個陣列,該如何處理呢?可以參考以下的方式:

var name = ["stanley", "jack", "anita" , "mary"];
var gender = ["male" , "male" , "female" , "female"];
var score = [30, 10, 40 , 80];
var ID = ["S1" , "S2" , "S3" , "S4"];

console.log("name : " + name + "; score : " + score + "; gender : " + gender + "; ID : " + ID);
/*
排序前
name : stanley,jack,anita,mary;
score : 30,10,40,80;
gender : male,male,female,female;
ID : S1,S2,S3,S4;
*/

var list = [];
for (var i = 0; i < name.length; i++){
  list.push({
    'name': name[i],
    'score': score[i],
    'gender': gender[i],
    'ID': ID[i]
  });
}

list.sort(function(a, b) {
  return ((a.name < b.name) ? -1 : ((a.name == b.name) ? 0 : 1));
});

for (var i = 0; i < list.length; i++) {
  name[i] = list[i].name;
  score[i] = list[i].score;
  gender[i] = list[i].gender;
  ID[i] = list[i].ID;
}

console.log("name : " + name + "; score : " + score + "; gender : " + gender + "; ID : " + ID);
/*
排序後
name : anita,jack,mary,stanley;
score : 40,10,80,30;
gender : female,male,female,male;
ID : S3,S2,S4,S1;
*/

若是希望按照分數排序,則可以將sort function 修改為下:

//score 由小到大
list.sort(function(a, b) {
  return a.score - b.score
});

//score 由大到小
list.sort(function(a, b) {
  return b.score - a.score
});

補充:

上述的排序內容均以英文和數字為主,若是遇到中文可使用localeCompare進行,而排序的方式是漢語拼音順序,以下為範例:

var arr = ["二","五","四","一","三"];
//漢語拼音:一[yi], 二[er], 三[san], 四[si], 五[wu]
console.log("排序前:" + arr); // 排序前:二,五,四,一,三
arr.sort(function(a,b){
	return a.localeCompare(b, 'zh'); //排序後:二,三,四,五,一
});
console.log("排序後:" + arr); 

var arr = ["中文","英語","法國話", "京片子", "中國"];
//中文[zhong wen], 英語[ying yu], 法國話[fa guo hua], 京片子[jing pian zi], 中國[zhong guo]
console.log("排序前:" + arr); //排序前:中文,英語,法國話,京片子,中國
arr.sort(function(a,b){
	return a.localeCompare(b, 'zh');
});
console.log("排序後:" + arr); //排序後:法國話,京片子,英語,中國,中文


var arr = ["中文","英语","法国话", "京片子", "中国"];
console.log("排序前:" + arr); //排序前:中文,英语,法国话,京片子,中国
arr.sort(function(a,b){
	return a.localeCompare(b, 'zh');
});
console.log("排序後:" + arr); //排序後:法国话,京片子,英语,中国,中文

You may also like...

11,197 Responses

  1. i would love to use hydrogen fuel on my car, this fuel is really nonpolluting but is not yet very available,

  2. It’s difficult to get knowledgeable men and women with this topic, and you appear to be what happens you are dealing with! Thanks

  3. I am often to blogging i actually appreciate your site content. The content has really peaks my interest. I am going to bookmark your web blog and maintain checking for brand new information.

  4. Sazrszq表示:

    Можно ли купить аттестат о среднем образовании? Основные рекомендации

    ecoheal.ru/index.php/jomsocial/groups/viewbulletin/388-nado-priobresti-diplom-posetite-luchshij-onlajn-magazin?groupid=1

  5. Sahabet表示:

    Sahabet Casino’da yeni oyuncular, en yuksek bonusu alarak oyun keyfini c?karabilir. En sevilen slotlar Sahabet’te en iyi odullerle dolu. Sans?n?z? simdi deneyin ve ilk depozitoda buyuk avantajlar kazan?n. Sahabet, 2024’un en karl? kumarhanesi olarak dikkat cekiyor.

    Sans?n?z? kac?rmay?n! Comert bonuslar talep edin ve Sahabet ile birlikte buyuk oduller kazan?n Unlu Sahabet Casino\’da yeni oyuncular icin en yuksek bonusu al?n .

  6. Thanks a lot for giving everyone an extraordinarily memorable chance to read in detail from this site. It is often so brilliant and packed with a lot of fun for me and my office acquaintances to search your site nearly thrice in a week to read through the latest items you will have. And definitely, I’m certainly astounded considering the exceptional ideas you serve. Certain two points in this post are really the most beneficial we’ve ever had.

  7. The the next occasion Someone said a blog, I really hope who’s doesnt disappoint me about this blog. After all, I know it was my choice to read, but I just thought youd have some thing intriguing to talk about. All I hear is really a number of whining about something you could fix in case you werent too busy seeking attention.

  8. Wohh just what I was searching for, appreciate it for putting up.

  9. I have been exploring for a little bit for any high quality articles or blog posts in this kind of house . Exploring in Yahoo I at last stumbled upon this site. Reading this information So i am glad to exhibit that I have a very excellent uncanny feeling I came upon just what I needed. I so much surely will make certain to do not put out of your mind this website and provides it a look a continuing.

  10. Audio began playing any time I opened up this webpage, so annoying!

  11. There couple of intriguing points in time in the following paragraphs but I don’t know if these center to heart. There’s some validity but I’ll take hold opinion until I look into it further. Great write-up , thanks and we want a lot more! Added onto FeedBurner also

  12. магазин электрокарнизов https://www.elektrokarniz2.ru .

  13. карниз электроприводом штор стоимость карниз электроприводом штор стоимость .

  14. LarrySwall表示:

    заказать разработку сайта под ключ недорого https://seo-5.ru

  15. Hi my loved one! I want to say that this article is amazing, great written and include almost all vital infos. I would like to peer more posts like this .

  16. Wow ~ Good stuff ~ Come and check out MY ??

  17. Great blog here! Also your website loads up fast! What host are you the usage of? Can I get your affiliate hyperlink for your host? I want my website loaded up as quickly as yours lol.

  18. AncrPaish表示:

    Urethra — an infection of the tube that empties urine from the bladder to the outside is called urethritis.
    Your privacy should be safeguarded when you sildenafil dosage timing you want to compare costs from pharmacies
    If results are positive, a colonoscopy is performed.

  19. Amazing blog! Do you have any suggestions for aspiring writers? I’m planning to start my own blog soon but I’m a little lost on everything. Would you propose starting with a free platform like WordPress or go for a paid option? There are so many choices out there that I’m completely confused .. Any suggestions? Bless you!

  20. карнизы для штор с электроприводом цена карнизы для штор с электроприводом цена .

  21. Judging by the way you write, you seem like a professional writer.,-~~;

  22. I do not even know the way I stopped up right here, however I thought this put up was good. I don’t understand who you’re but certainly you are going to a famous blogger when you are not already Cheers!

  23. Getting a issue with the Feed, could you help me?

  24. Oh my goodness! an incredible article dude. Thanks a ton However We are experiencing issue with ur rss . Don’t know why Cannot enroll in it. Can there be any person finding identical rss dilemma? Anyone who knows kindly respond. Thnkx

  25. Fantastic, thanks for the awesome article. I’m having troubles subscribing to your blogs feed. Thought I’d let you know

  26. Substantially, the article is really the freshest on that valuable topic. I match in with your conclusions and definitely will eagerly look forward to your next updates. Saying thanks definitely will not just be acceptable, for the amazing clarity in your writing. I will certainly immediately grab your rss feed to stay privy of any updates. Authentic work and also much success in your business efforts!

  27. Your passion for this topic is contagious! After reading your blog post, I can’t wait to learn more.

  28. You ought to get involved in a contest for starters of the most useful blogs online. I am going to suggest this blog!

  29. Rachel Weisz have that mysterious look and she is very appealing to most men and women,,

  30. Cazrarm表示:

    Всё, что нужно знать о покупке аттестата о среднем образовании

    almatykitap.kz/content/pgs/?gde_kupit_originalnuy_diplom_v_rf_legalno_i_bezopasno

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。