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

7,871 Responses

  1. its great as your other articles : D, regards for posting .

  2. CraigHeala表示:

    The fascinating story of the creation and meteoric rise of Amazon https://amazon.jeff-bezos-fr.com from its humble beginnings as an online bookstore to its dominant force in the world of e-commerce.

  3. Some really interesting info , well written and loosely user genial .

  4. Qdjrou表示:

    leflunomide canada – order generic actonel 35 mg buy cartidin pill

  5. carpenter bee表示:

    you have a excellent blog here! do you want to develop invite posts in this little weblog?

  6. Good day! I could have sworn I’ve visited this web site before but after going through a few of the articles I realized it’s new to me. Regardless, I’m certainly happy I came across it and I’ll be bookmarking it and checking back often.

  7. I could not refrain from commenting. Very well written!

  8. Jimmyplobe表示:

    Olympique de Marseille https://liga1.marseilles-fr.com after several years in the shadows, once again becomes champion of France. How did they do it and what prospects open up for the club

  9. dead bed bug表示:

    you have a very fantastic blog here! do you wish to have the invite posts on my small weblog?

  10. This site really has all of the info I wanted about this subject and didn’t know who to ask.

  11. Larryhax表示:

    The fascinating story of Gigi Hadid’s rise to Victoria’s Secret Angel https://victorias-secret.gigi-hadid-fr.com status and her journey to the top of the modeling industry.

  12. MatthewGault表示:

    Travel to the pinnacle of French football https://stadede-bordeaux.bordeaux-fr.org at the Stade de Bordeaux, where the passion of the game meets the grandeur of architecture.

  13. Robertedize表示:

    Parisian PSG https://paris.psg-fr.com is one of the most successful and ambitious football clubs in Europe. Find out how he became a global football superstar.

  14. kill rats表示:

    “Having read this I thought it was very informative. I appreciate you taking the time and effort to put this article together. I once again find myself spending way to much time both reading and commenting. But so what, it was still worth it!”

  15. Best Keyphrase Research Tips – Few Untapped Keyword
    Research Techniques 검색엔진최적화 대행사

  16. ErwinVak表示:

    Une ascension fulgurante au pouvoir Donald Trump https://usa.donald-trump-fr.com et son empire commercial

  17. RichardGew表示:

    Max Verstappen and Red Bull Racing’s https://red-bull-racing.max-verstappen-fr.com path to success in Formula 1. A story of talent, determination and team support leading to a championship title.

  18. RobertIdior表示:

    The astonishing story of Emmanuel Macron’s https://president-of-france.emmanuel-macron-fr.com political rise from bank director to the highest office in France.

  19. Marionskibe表示:

    Kim Kardashian’s https://the-kardashians.kim-kardashian-fr.com incredible success story, from sex scandal to pop culture icon and billion-dollar fortune.

  20. sex表示:

    Pretty! This was an extremely wonderful post. Many thanks for providing this info.

  21. kontol besar表示:

    Aw, this was an incredibly nice post. Finding the time and actual effort to produce a good article… but what can I say… I put things off a whole lot and don’t manage to get nearly anything done.

  22. Things To Take Into Consideration Before You Employ A Car Loan 저신용자 대출

  23. FrankCarry表示:

    The fascinating story of the creation and rapid growth of Facebook https://facebook.mark-zuckerberg-fr.biz under the leadership of Mark Zuckerberg, who became one of the most influential technology entrepreneurs of our time.

  24. TimothyGek表示:

    The legendary boxing world champion Mike Tyson https://ufc.mike-tyson-fr.biz made an unexpected transition to the UFC in 2024, where he rose to the top, becoming the oldest heavyweight champion.

  25. JustinEmomi表示:

    The fascinating story of how Lewis Hamilton https://mercedes.lewis-hamilton-fr.biz became a seven-time Formula 1 world champion after signing with Mercedes.

  26. CharlesNig表示:

    The story of Fernando Alonso https://formula-1.fernando-alonso-fr.com in Formula 1: a unique path to success through talent, tenacity and strategic decisions, inspiring and exciting.

  27. AndreKnism表示:

    The powerful story of Conor McGregor’s https://ufc.conor-mcgregor-fr.biz rise to a two-division UFC championship that forever changed the landscape of mixed martial arts.

  28. Lunrmvm表示:

    Привет!
    Мы изготавливаем дипломы любой профессии по разумным тарифам.
    Мы можем предложить документы ВУЗов, расположенных в любом регионе России. Можно купить диплом за любой год, указав актуальную специальность и оценки за все дисциплины. Документы печатаются на “правильной” бумаге самого высокого качества. Это дает возможность делать настоящие дипломы, которые невозможно отличить от оригиналов. Они заверяются необходимыми печатями и штампами.
    Даем гарантию, что при проверке документов работодателями, никаких подозрений не возникнет.
    Где купить диплом специалиста?
    elfae.ruhelp.com/viewtopic.php?id=6925#p25970

  29. Briantes表示:

    Добрый день!
    Заказать диплом ВУЗа.
    Мы предлагаем заказать диплом в отличном качестве, неотличимый от оригинального документа без использования дорогостоящего оборудования и квалифицированного специалиста.
    Где купить диплом по необходимой специальности?
    http://domovou.3nx.ru/login.php?redirect=posting.php&mode=newtopic&f=23
    Успешной учебы!

  30. ngentot memek表示:

    Howdy! This post couldn’t be written much better! Going through this post reminds me of my previous roommate! He continually kept preaching about this. I will send this information to him. Pretty sure he’ll have a good read. Thank you for sharing!

發佈留言

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