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

9,132 Responses

  1. For instance, generate suppliers have worked with the Meals & Drug Administration (FDA) to make confident that the industry requirements created outcome in the most effective and most successful processes. And to communicate any public announcements, the sector has formulated relationships with associations like the Nationwide Grocer’s Association (NGA).

  2. Hey, I just started reading your blog – thank you for writing. As an FYI that it’s not displaying properly on the BlackBerry Browser (I have a Pearl). Anyway, I’m now subscribed to your RSS feed on my laptop, so thanks again!

  3. very nice put up, i actually love this website, carry on it

  4. Percylelay表示:

    AI Nude Generator https://ainudegenerator.app Transform Photos with AI Nude App.

  5. Why Adding A Demo Slot Zeus Gratis To Your Life’s Journey Will Make The Different slot demo zeus gacor maxwin (https://glamorouslengths.com/)

  6. Excellent stuff. I can’t describe how much your site has helped me within my academic research on the subject. I’m now likely to get top marks without a doubt. Thanks a thousand. I owe you one.

  7. What’s The Job Market For Treadmill Near Me Professionals?
    treadmill near me

  8. I love the efforts you have put in this, appreciate it for all the great articles .

  9. leak tracing表示:

    When I originally commented I clicked the -Notify me when new comments are added- checkbox now every time a comment is added I get four emails concentrating on the same comment. Can there be by any means you are able to remove me from that service? Thanks!

  10. I have been reading out a few of your posts and i must say nice stuff. I will surely bookmark your site.

  11. Mazroxj表示:

    Здравствуйте!
    Всё, что нужно знать о покупке аттестата о среднем образовании
    diploms-man.ru

  12. Hello. I want to ask a little something…is this a wordpress website as we are planning to be switching across to WP. In addition did you make this theme by yourself? Appreciate it.

  13. You have talked some nice information on the subject, are you working to do a FAQ about this issue in the future, as i have some more doubts that will be common to other readers.

  14. Hello, i think that i saw you visited my site so i came to “return the favor”.I am attempting to find things to enhance my site!I suppose its ok to use a few of your ideas!!

  15. Uazrkoo表示:

    Привет, друзья!
    Купить диплом любого университета.
    http://www.ladymystery.ru/forum/topic.asp?TOPIC_ID=9523

  16. Hello, very intriguing posting. My niece and I have been recently looking to find comprehensive facts about this sort of stuff for a while, nevertheless we couldn’t until now. Do you consider you can make several youtube video clips about this, I do think your web blog could well be more detailed in case you did. If not, oh well. I’ll be checking out on this site in the near future. E-mail me to keep me updated. granite countertops cleveland

  17. Dnrtozp表示:

    Привет, друзья!
    Заказать документ о получении высшего образования можно в нашей компании в столице.
    diplomasx24.ru/kupit-diplom-omsk
    Хорошей учебы!

  18. Quite insightful post. Never believed that it was this simple after all. I had spent a very good deal of my time looking for someone to explain this topic clearly and you’re the only one that ever did that. Kudos to you! Keep it up

  19. Giving you the best News is very much imptortant to us.

  20. I’m not sure exactly how I discovered your blog because I had been researching information on Real Estate in Lake Mary, FL, but anyway, I have had a pleasant time reading it, keep it up!

  21. Lazrpvx表示:

    Здравствуйте!
    Приобрести диплом о высшем образовании.
    yur-dom.ru/communication/forum/messages/forum3/message242/285-bolshoy-vybor-dokumentov-v-izvestnom-internet_magazine?result=new

  22. Trefnjr表示:

    Привет, друзья!
    Реально ли приобрести диплом стоматолога? Основные шаги
    rdcvw.com/space-uid-320969
    Рады оказать помощь!.

  23. Diplomi_ztEa表示:

    Привет, друзья!
    Приобрести документ о получении высшего образования можно у нас в столице.
    ast-diplomy.com/kupit-diplom-perm

  24. Lazrene表示:

    Привет!
    Мы предлагаем дипломы психологов, юристов, экономистов и любых других профессий по приятным тарифам.
    newsinweek.ru/kupit-ofitsialnyiy-diplom-s-garantiey

  25. I do accept as true with all of the ideas you’ve offered on your post. They are very convincing and will certainly work. Nonetheless, the posts are too short for beginners. Could you please prolong them a little from next time? Thanks for the post.

  26. JamesApold表示:

    Discover Kyrie Irving’s https://mavericks-de-dallas.kyrie-irving-fr.com journey with the Dallas Mavericks, from his early days to forming a power duo with Luka Doncic and competing for a championship.

  27. KevinInove表示:

    Mavericks rising superstar Luka Doncic https://mavericks-de-dallas.lukadoncic-fr.com continues to amaze the basketball world with his game.

  28. Mazrrms表示:

    Добрый день!
    Приобрести документ института можно в нашей компании. Мы оказываем услуги по изготовлению и продаже документов об окончании любых университетов Российской Федерации. Вы сможете получить необходимый диплом по любой специальности, включая документы СССР. Даем 100% гарантию, что в случае проверки документа работодателем, подозрений не появится.
    Мы изготавливаем дипломы любых профессий по приятным ценам. Цена будет зависеть от выбранной специальности, года получения и университета. Стараемся поддерживать для заказчиков адекватную ценовую политику. Важно, чтобы документы были доступными для подавляющей массы наших граждан.
    formfinance.ru/kupit-diplom-v-internete-legalno-i-konfidentsialno
    Рады помочь!

  29. Hi there, thanks for the awesome posting. I’m having troubles subscribing to your blogs feed. Thought I’d let you know

  30. Thomasnag表示:

    The story of Michael Phelps https://amerique.michael-phelps.com how he became the greatest swimmer of all time, overcoming adversity, setting records and inspiring the world.

發佈留言

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