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

  1. Why Everyone Is Talking About Toto Online Terbaik Right Now Bandar togel terpercaya

  2. 4 Dirty Little Tips On The Integrated Fridgefreezer
    Industry Built In fridge Freezers 50/50

  3. Having read this I believed it was rather informative. I appreciate you taking the time and energy to put this content together. I once again find myself spending a lot of time both reading and commenting. But so what, it was still worthwhile!

  4. AndrewRaike表示:

    дезинфекция квартиры после смерти цена https://dezinfekciya-posle-smerti.ru/

  5. Dxnofv表示:

    buy voveran tablets – buy generic nimodipine buy nimotop without a prescription

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

  7. The basic equipment which are required throughout creating MOTORHOME sun power panels are really a Cost Controller, an Inverter, an important storage devices power supply and naturally, a fabulous solar cell.

  8. электрокарниз дешево http://www.elektrokarniz2.ru .

  9. You seem to be very professional in the way you write.;.;’:

  10. Aw, this was a very good post. Spending some time and actual effort to generate a top notch article… but what can I say… I hesitate a lot and don’t manage to get anything done.

  11. I have learn several good stuff here. Definitely worth bookmarking for revisiting. I wonder how a lot attempt you put to make this kind of excellent informative website.

  12. Guide To Psychiatrist Assessment Near Me: The Intermediate Guide The Steps To Psychiatrist Assessment Near Me Psychiatrist assessment near Me

  13. Treehouse Bunk Tips From The Best In The Industry tree house toddler bed

  14. Can I simply say what a reduction to seek out somebody who actually knows what theyre talking about on the internet. You definitely know tips on how to convey an issue to mild and make it important. More people have to learn this and perceive this side of the story. I cant imagine youre no more standard since you definitely have the gift.

  15. Aw, this was a very nice post. In idea I wish to put in writing like this additionally ? taking time and precise effort to make a very good article? but what can I say? I procrastinate alot and not at all appear to get something done.

  16. Sink repair表示:

    This is the appropriate weblog for wishes to be made aware of this topic. You already know a great deal its nearly not easy to argue along (not that I really would want…HaHa). You certainly put a different spin with a topic thats been revealed for years. Excellent stuff, just great!

  17. OscarGed表示:

    Offre speciale 1xBet Obtenez un bonus sportif supplementaire de 200% jusqu’a 130 €/$ avec le Code Promo Niger, en plus du bonus de bienvenue standard de 1950$ et de 150 tours gratuits au casino. Profitez de cette opportunite pour jouer et gagner de l’argent grace aux paris sportifs. Chez nous, tout le monde peut devenir gagnant !

  18. рулонные шторы с автоматическим управлением рулонные шторы с автоматическим управлением .

  19. электрические шторы и тюли http://elektrokarniz2.ru/ .

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

  21. 오피表示:

    Your passion for this topic is contagious.오피

  22. El comercio de opciones binarias permite realizar predicciones financieras en la que los inversores predicen si el valor de un activo se mantendra o cambiara. Brokers regulados como Quotex ofrecen una plataforma intuitiva para el trading de opciones binarias. Utilizando indicadores y analisis, es posible aumentar las ganancias en el trading de opciones binarias. El comercio de opciones binarias se ha vuelto frecuente en paises como Mexico y en todo el mundo.
    quotex broker iniciar sesion quotex .

  23. You are so interesting! I don’t believe I have read anything like this before. So wonderful to discover another person with original thoughts on this subject. Seriously.. many thanks for starting this up. This site is something that’s needed on the web, someone with a bit of originality.

  24. Chu表示:

    Are Kids Bunkbed The Best Thing There Ever Was? bunk beds for kids; Chu,

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

  26. After looking over a few of the blog posts on your web site, I really appreciate your way of writing a blog. I book marked it to my bookmark site list and will be checking back soon. Please visit my web site too and tell me your opinion.

  27. inspiring insights you are sharing. I love the way you are sharing it. Is there any way I could get updated for more?

發佈留言

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