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

24,142 Responses

  1. DichaelDax表示:

    What’s up i am kavin, its my first time to commenting anywhere, when i read this post i thought i could also make comment due to this sensible paragraph.
    top 10 online pokies australia

  2. Timsothyabela表示:

    Hello there! Do you use Twitter? I’d like to follow you if that would be okay. I’m undoubtedly enjoying your blog and look forward to new posts.
    new online casinos listings

  3. ALhaneevige表示:

    Hello I am so grateful I found your website, I really found you by accident, while I was looking on Yahoo for something else, Anyhow I am here now and would just like to say thanks a lot for a fantastic post and a all round interesting blog (I also love the theme/design), I don’t have time to look over it all at the minute but I have bookmarked it and also added your RSS feeds, so when I have time I will be back to read a great deal more, Please do keep up the great work.
    online casino australia reviews

  4. AShaneevige表示:

    What you composed made a ton of sense. But, consider this, what if you were to create a awesome title? I am not saying your information isn’t solid., but suppose you added something to maybe get folk’s attention? I mean %BLOG_TITLE% is kinda boring. You might look at Yahoo’s front page and note how they create news titles to grab viewers interested. You might add a video or a related picture or two to grab people interested about everything’ve written. In my opinion, it could make your posts a little bit more interesting.
    cryptocurrency casinos

  5. DichaelDax表示:

    Hey this is kind of of off topic but I was wanting to know if blogs use WYSIWYG editors or if you have to manually code with HTML. I’m starting a blog soon but have no coding know-how so I wanted to get advice from someone with experience. Any help would be enormously appreciated!
    whats plinko

  6. Kneuae表示:

    brand orlistat 120mg purchase diltiazem pills diltiazem brand

  7. DichaelDax表示:

    Zeolite Heavy Equipment LLC offers a comprehensive range of industrial equipment for various industries. We provide reliable solutions to meet the needs of our customers, ensuring their satisfaction with our products and services. Our company is dedicated to delivering exceptional value and service to our customers.

  8. Timsothyabela表示:

    Tremendous things here. I’m very satisfied to see your article. Thank you a lot and I am having a look ahead to touch you. Will you please drop me a mail?
    miramax casino

  9. EarnestAvada表示:

    Pretty! This was an incredibly wonderful article. Thank you for supplying this info.
    live casino app

  10. Uljcgu表示:

    metformin 500mg ca order metformin 1000mg online buy glycomet

  11. Mgxexs表示:

    priligy 60mg over the counter buy generic misoprostol online buy generic misoprostol

  12. Skpflc表示:

    buy chloroquine 250mg online purchase chloroquine generic buy chloroquine 250mg generic

  13. Kdnllf表示:

    buy claritin generic loratadine 10mg generic claritin where to buy

  14. Cgtvzx表示:

    cenforce 50mg for sale brand cenforce 50mg purchase cenforce online

  15. Lzwlkq表示:

    buy clarinex 5mg online clarinex cheap buy clarinex 5mg pill

  16. OLaneevige表示:

    Thank you a lot for sharing this with all folks you really understand what you’re talking approximately! Bookmarked. Kindly also consult with my website =). We can have a hyperlink change contract among us
    cloudbet soccer

  17. Myfuic表示:

    order tadalafil 10mg pills tadalafil over the counter order tadalafil 20mg

  18. StephenDeery表示:

    For most up-to-date information you have to visit the web and on the web I found this web page as a best site for most up-to-date updates.
    https://secure.squirtingvirgin.com/track/MzAxODgyLjUuMjguMjguMC4wLjAuMC4w

  19. StephenDeery表示:

    Marvelous, what a blog it is! This weblog gives helpful facts to us, keep it up.
    mbit casino reddit

  20. Ydomvo表示:

    buy triamcinolone triamcinolone for sale online how to buy aristocort

  21. Waedjj表示:

    plaquenil for sale online order hydroxychloroquine 200mg generic buy hydroxychloroquine generic

  22. Umhpfo表示:

    buy generic lyrica online purchase pregabalin pills order lyrica generic

  23. Xuguqd表示:

    levitra 20mg canada vardenafil order levitra canada

  24. Oukjoh表示:

    poker games online slot games free roulette online for real money

  25. Gjwipc表示:

    order semaglutide pills order generic semaglutide semaglutide price

  26. Rixrqt表示:

    cheap doxycycline doxycycline without prescription monodox drug

  27. SDichaelDax表示:

    Comprar Cialis Generico
    (Admin)
    Cialis 5 mg prezzo tadalafil 5 mg prezzo tadalafil 5 mg prezzo

  28. Gvoifu表示:

    buy viagra 50mg pill cheapest viagra buy viagra 100mg for sale

發佈回覆給「Kneuae」的留言 取消回覆

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