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...

8,871 Responses

  1. LloydFAING表示:

    helium balloons for birthday buy balloons cheap

  2. Kennethmab表示:

    Официальный телеграм Sykaaa предлагает новым игрокам бонус 325% в 4 этапа, за активное повышение уровня – игрок получает кэшбэк и быстрые выводы. Новых пользователей привлекает не только бонус бездеп за регистрацию, но и дизайн https://t.me/s/sykaaa_official_casino на сайте наглядное меню, которое позволяет в пару кликов найти нужный провайдер, выбрать игровой автомат или сделать депозит.

  3. Ta very much for the update, extremely useful. Do you thoughts If I can I use an extract or two on my web page?

  4. Hi! Do you know if they make any plugins to help with SEO? I’m trying to get my blog to rank for some targeted keywords but I’m not seeing very good results. If you know of any please share. Thank you!

  5. A motivating discussion is definitely worth comment. I do think that you should write more on this topic, it might not be a taboo matter but generally people do not discuss such topics. To the next! Kind regards!

  6. Thank her so much! This line is move before dovetail crazy, altarpiece rather act like habitual the economizing – what entrepreneur groovy night until deal with starting a trade.

  7. thank you dearly author , I found oneself this web site very helpful and its full of excellent healthy selective information ! , I as well thank you for the fantastic food plan post.

  8. Hi, I do think this is an excellent website. I stumbledupon it 😉 I will revisit once again since I saved as a favorite it. Money and freedom is the best way to change, may you be rich and continue to help others.

  9. We’re glad to be a visitor of your thoroughgoing webpage, regards due to this rare info!

  10. eating disorders are of course sometimes deadly because it can cause the degeneration of one’s health~

  11. This is a very good tip especially to those new to the blogosphere. Short but very precise info… Appreciate your sharing this one. A must read article.

  12. A motivating discussion is definitely worth comment. I believe that you should publish more on this subject, it may not be a taboo subject but usually people don’t talk about such topics. To the next! Cheers.

  13. Wow, I guess you do learn something new everyday, more people should stumble onto this! You need some good SEO work!

  14. Профессиональный сервисный центр по ремонту планетов в том числе Apple iPad.
    Мы предлагаем: ремонт планшетов айпад в москве
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  15. I was just seeking this information for a while. After six hours of continuous Googleing, finally I got it in your website. I wonder what is the lack of Google strategy that do not rank this type of informative web sites in top of the list. Usually the top sites are full of garbage.

  16. Sazruia表示:

    Аттестат 11 класса купить официально с упрощенным обучением в Москве
    veganxyz.mn.co/posts/65295404

  17. Thank you for yet another great informative article, I’m a loyal reader to this blog and I can’t stress enough how much valuable information I’ve learned from reading your content. I really appreciate all the hard work you put into this great site.

  18. Can I say what a relief to discover one who actually knows what theyre preaching about on-line. You certainly understand how to bring a challenge to light making it important. More and more people really need to check out this and understand why side of your story. I cant believe youre less well-known simply because you undoubtedly develop the gift.

  19. consumer electronics these days are mostly composed of gadgets that are more into phones and internet connection*

  20. Appreciating the persistence you’d put in to the blog – Gulvafslibning | Kurt Gulvmand as well as in depth information you present… It’s good to come upon a different blog once in a while that is not similar unwanted re-written material. Great read. I’ve bookmarked your blog post and I’m adding your Rss feeds to my Bing address … FYI what about Egypt wonderful tv news…

  21. Can I simply say what a comfort to discover a person that genuinely understands what they are discussing on the net. You certainly realize how to bring a problem to light and make it important. More and more people ought to look at this and understand this side of your story. I was surprised that you are not more popular because you surely have the gift.

  22. HerbertemuRl表示:

    hi guys i say that https://wplgsturapwmestv185.ru/

  23. Lazrbwy表示:

    Привет, друзья!
    Мы готовы предложить дипломы любых профессий по приятным тарифам.
    dancerussia.ru/forum/viewtopic.php?p=23110

  24. Cazrwpn表示:

    Приобретение диплома ВУЗа с сокращенной программой обучения в Москве
    sbereg.ru/pages/gde_kupit_provedennuy_diplom_v_moskve_legalno_i_bustro

  25. TS Escorts表示:

    Hi! I could have sworn I’ve been to this website before but after looking at some of the posts I realized it’s new to me. Anyhow, I’m certainly happy I stumbled upon it and I’ll be book-marking it and checking back frequently.

  26. Randallabevy表示:

    вавада cazinosvavada777z cazinosvavada777z top https://sertifikaliegitimler.com

發佈留言

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