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

  1. 10 Things Your Competition Can Teach You About Replacement Volkswagen Keys volkswagen passat key replacement cost

  2. Scottdycle表示:

    Дезинфекция после смерти цена https://dezinfekciya-ot-smerti-msk.ru/

  3. Luciana表示:

    How To Become A Prosperous Stove When You’re Not Business-Savvy 5829186 (Luciana)

  4. PatrickLef表示:

    gel per erezione in farmacia: viagra senza prescrizione – cialis farmacia senza ricetta

  5. Sasha表示:

    See What Bulk Arabica Coffee Beans Tricks The Celebs Are Making Use Of bulk
    arabica coffee beans – Sasha

  6. PatrikNom表示:

    прикольные мемы в приложении
    Всё шуточки

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

  8. Tawnya表示:

    7 Things You Never Knew About Electric Wheelchair Benefits electric
    light weight wheelchair (Tawnya)

  9. Edisonanazy表示:

    Farmacia online piГ№ conveniente: Farmacie on line spedizione gratuita – Farmacie on line spedizione gratuita

  10. 9324874表示:

    The Reason Why You’re Not Succeeding At Top Single Strollers 9324874

  11. Beatrice表示:

    How To Find The Perfect Skoda Citigo Replacement Key On The Internet skoda replacement
    key (Beatrice)

  12. AvtyHesia表示:

    Hi DP, I always have regular periods, and my partner says that he notices me start to PMS about ten days before my period starts.
    An internet store has levitra online buy you can save even more when you get generic.
    There is evidence that both men and women who gain weight in adulthood increase their risk of diabetes.

  13. AdmdHesia表示:

    Saath hi saath gardan mai gath banjati hai aur gale mai kharash bani rehti hai.
    Be sensitive about ED patients. mexican pharmacy viagra online are small businesses.
    This type of hernia is more common in women due to pregnancy, and in Chinese and black infants.

  14. Geneva表示:

    The 3 Most Significant Disasters In Replacement Skoda Key History replacement
    car keys skoda – Geneva,

  15. Если вы искали где отремонтировать сломаную технику, обратите внимание – ремонт бытовой техники в уфе

  16. Niamh表示:

    This Is How Replacement Mini Key Fob Will Look In 10 Years’
    Time mini countryman key fob (Niamh)

  17. Vallie表示:

    You’ll Never Guess This Adult Adhd Assessment Uk’s Tricks
    adhd assessment uk (Vallie)

  18. Edisonanazy表示:

    le migliori pillole per l’erezione: dove acquistare viagra in modo sicuro – gel per erezione in farmacia

  19. The next occasion Someone said a weblog, I’m hoping which it doesnt disappoint me approximately this. I mean, It was my solution to read, but I really thought youd have some thing interesting to talk about. All I hear is often a couple of whining about something that you could fix if you ever werent too busy trying to find attention.

  20. I would like to thnkx for the efforts you have put in writing this site. I am hoping the same high-grade site post from you in the upcoming also. Actually your creative writing skills has encouraged me to get my own web site now. Actually the blogging is spreading its wings rapidly. Your write up is a great example of it.

  21. Saniflo WCs表示:

    I and also my pals happened to be checking out the nice tips and hints on the website then instantly came up with a terrible suspicion I had not expressed respect to the site owner for those secrets. Most of the women ended up warmed to learn all of them and have seriously been taking pleasure in those things. Appreciate your actually being quite considerate as well as for choosing some superior resources most people are really wanting to be informed on. My personal sincere apologies for not expressing appreciation to you sooner.

  22. Hello There. I found your blog the use of msn. This is an extremely smartly written article. I’ll be sure to bookmark it and return to read more of your useful info. Thanks for the post. I will definitely comeback.

  23. Kandis表示:

    Why Incorporating A Word Or Phrase Into Your Life’s Journey
    Will Make The Difference anxiety attack treatment without medication; Kandis,

  24. Edisonanazy表示:

    farmacie online sicure: Farmacie che vendono Cialis senza ricetta – migliori farmacie online 2024

  25. gas plumber表示:

    I have not checked in here for some time since I thought it was getting boring, but the last few posts are great quality so I guess I¡¦ll add you back to my everyday bloglist. You deserve it my friend pristina travel

  26. Thanks for helping out, good info .

  27. nearby表示:

    How To Determine If You’re Ready To Go After Hyundai
    I10 Key nearby

  28. Попробуйте свою удачу в lex casino, где у вас есть шанс выиграть миллионы.
    Проверенное казино lex ждет вас, которая принесет вам удовольствие и возможность заработать.
    Откройте для себя новое казино lex, где каждый может стать победителем.
    Бонусы и акции от lex casino ждут вас, позволяющие вам увеличить свой баланс.
    Попробуйте удачу в lex casino прямо сейчас, где вас ждут захватывающие сюжеты и крупные джекпоты.
    lex casino промокод фриспины лекс казино официальный .

發佈留言

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