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,839 Responses

  1. Seven To Be Able To Credit Card Death 개인회생 대출 (http://www.smmconnect.com)

  2. This Is How Slot Demo Gratis Sugar Rush Will Look Like In 10 Years’ Time sugarrush demo –
    alonegocio.net.br

  3. 023456789.xyz表示:

    15 Best Documentaries About Cheapest 10kg Washing Machines 023456789.xyz

  4. hishypesports表示:

    This is a really good tip especially to those new to the blogosphere. Short but very accurate info… Thank you for sharing this one. A must read post.

  5. How To Create An Awesome Instagram Video About Veterans Disability Attorney veterans disability Lawyer

  6. 10 Meetups About Nissan Juke Key Replacement You Should Attend how Much is a replacement key for nissan qashqai (https://posteezy.com/)

  7. AndreEmubs表示:

    Football in Saudi Arabia https://al-hilal.saud-abdulhamid-ar.com is gaining more and more popularity and recognition on the international stage, and Saud Abdul Hamid, the young and talented defender of Al Hilal, is a shining example of this success.

  8. I seriously love your site.. Excellent colors & theme. Did you build this web site yourself? Please reply back as I’m wanting to create my own personal blog and would love to learn where you got this from or just what the theme is called. Appreciate it.

  9. The 10 Most Terrifying Things About Upvc Windows Repairs upvc windows repairs

  10. This Week’s Top Stories About Best Electric Wheelchair For Travel Best Electric Wheelchair For Travel Wheelchair Electric Lightweight

  11. WestonRor表示:

    Khvicha Kvaratskhelia https://napoli.khvicha-kvaratskhelia-ar.com is a name that in recent years has become a symbol of Georgian football talent and ambition.

  12. Phillipbrofs表示:

    Angel Di Maria https://benfica.angel-di-maria-ar.com is a name that will forever remain in the memories of Benfica fans.

  13. JohnnieBrupe表示:

    Roberto Firmino https://al-ahli.roberto-firmino-ar.com one of the most talented and famous Brazilian footballers of our time, has paved his way to success in different leagues and teams.

  14. Robertbeink表示:

    Maria Sharapova https://tennis.maria-sharapova-ar.com was born on April 19, 1987 in Nyagan, Russia. When Masha was 7 years old, her family moved to Florida, where she started playing tennis.

  15. Way cool! Some extremely valid points! I appreciate you penning this write-up and also the rest of the site is also really good.

  16. 10 Things That Your Family Taught You About Veterans Disability
    Lawyer veterans disability Lawyer

  17. game iwin表示:

    A fascinating discussion is definitely worth comment. I believe that you ought to write more on this topic, it may not be a taboo matter but generally people do not discuss such subjects. To the next! All the best.

  18. Legal表示:

    10 Apps To Help You Control Your Medical Malpractice Litigation Legal

  19. 학생 대출表示:

    Pre Approved Auto Loans Make The Car Loan Process Pleasurable 학생 대출

  20. iwin表示:

    I could not refrain from commenting. Very well written.

  21. 11 Ways To Completely Revamp Your Replace Upvc Window Handle
    upvc windows Repair near Me

  22. GeorgeStogs表示:

    Muhammad Al Owais https://al-hilal.mohammed-alowais-ar.com is one of the most prominent names in modern Saudi football. His path to success in Al Hilal team became an example for many young athletes.

  23. ChrisNom表示:

    Luis Diaz https://liverpool.luis-diaz-ar.com is a young Colombian striker who has enjoyed rapid growth since joining the ” Liverpool” in January 2022.

  24. Wesleycrins表示:

    Kevin De Bruyne https://manchester-city.kevin-de-bruyne-ar.com is a name every football fan knows today.

  25. Qazrlxl表示:

    Привет, друзья!
    Как получить диплом техникума с упрощенным обучением в Москве официально.
    Приобрести диплом о высшем образовании.
    8eg56er3s.blog5.net/70052601/%D0%A1-%D0%BB%D0%B5%D0%B3%D0%BA%D0%BE%D1%81%D1%82%D1%8C%D1%8E-%D0%BF%D0%BE%D0%BA%D1%83%D0%BF%D0%B0%D0%B5%D0%BC-%D0%B4%D0%B8%D0%BF%D0%BB%D0%BE%D0%BC-%D0%B2-%D0%BB%D1%83%D1%87%D1%88%D0%B5%D0%BC-%D0%BE%D0%BD%D0%BB%D0%B0%D0%B9%D0%BD-%D0%BC%D0%B0%D0%B3%D0%B0%D0%B7%D0%B8%D0%BD%D0%B5-russian-diplom

  26. ngentot pepek表示:

    This is a topic which is near to my heart… Best wishes! Exactly where can I find the contact details for questions?

  27. sex表示:

    I could not refrain from commenting. Perfectly written!

  28. WalterGed表示:

    In 2018, the basketball world witnessed one of the most remarkable transformations in NBA history. LeBron James https://los-angeles-lakers.lebronjames-ar.com one of the greatest players of our time, decided to leave his hometown Cleveland Cavaliers and join the Los Angeles Lakers.

  29. sex表示:

    This is the perfect blog for everyone who wishes to understand this topic. You know a whole lot its almost tough to argue with you (not that I actually would want to…HaHa). You certainly put a fresh spin on a subject that has been written about for years. Great stuff, just wonderful.

發佈留言

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