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

  1. THC gummies表示:

    Aw, this was a very nice post. Taking the time and actual effort to create a really good article… but what can I say… I put things off a lot and never seem to get anything done.

  2. Flum vape表示:

    You should take part in a contest for one of the greatest sites on the internet. I will highly recommend this site!

  3. Lazreqw表示:

    Привет!
    Мы изготавливаем дипломы любой профессии по разумным тарифам.
    http://www.greendoorkitchen.com/2024/06/25/диплом-университета-купил/

  4. CalvinTom表示:

    Juventus Football Club https://italy.juventus-ar.com is one of the most successful and decorated clubs in the history of Italian and world football.

  5. Donaldcrade表示:

    Chelsea https://england.chelsea-ar.com is one of the most successful English football clubs of our time.

  6. WilliamseF表示:

    The history of one of France’s https://france.paris-saint-germain-ar.com most famous football clubs, Paris Saint-Germain, began in 1970, when capitalist businessmen Henri Delaunay and Jean-Auguste Delbave founded the club in the Paris Saint-Germain-en-Laye area.

  7. DonaldTek表示:

    Zinedine Zidane https://real-madrid.zinedine-zidane-ar.com the legendary French footballer, entered the annals of football history as a player and coach.

  8. Jamescef表示:

    Travis Scott https://astroworld.travis-scott-ar.com is one of the brightest stars in the modern hip-hop industry.

  9. vents表示:

    That is a really good tip particularly to those new to the blogosphere. Short but very precise info… Thank you for sharing this one. A must read post!

  10. Cazrzdm表示:

    Добрый день!
    Мы можем предложить документы техникумов, которые находятся на территории всей Российской Федерации. Можно купить качественный диплом за любой год, указав необходимую специальность и оценки за все дисциплины. Документы выпускаются на “правильной” бумаге высшего качества. Это дает возможности делать государственные дипломы, которые невозможно отличить от оригиналов. Они будут заверены всеми обязательными печатями и штампами.
    http://www.cyberpinoy.net/read-blog/33705

  11. Lariorkir表示:

    Узнайте стоимость диплома высшего и среднего образования и процесс получения
    ast-diplomy24.ru/kupit-diplom-rostov-na-donu

  12. Trefudk表示:

    Добрый день!
    Аттестат 11 класса купить официально с упрощенным обучением в Москве
    odessaflower.ukrbb.net/viewtopic.php?f=55&t=29565
    Поможем вам всегда!.

  13. ontario表示:

    I seriously love your website.. Pleasant colors & theme. Did you make this web site yourself? Please reply back as I’m hoping to create my own personal website and would like to learn where you got this from or just what the theme is called. Cheers.

  14. Very good post! We are linking to this particularly great post on our website. Keep up the great writing.

  15. 99811760.xyz表示:

    One Of The Most Untrue Advices We’ve Ever Heard About Make Spare Car Key 99811760.xyz

  16. fobs表示:

    Why The Biggest “Myths” About Vauxhall Insignia Key Fob May Actually Be Right fobs

  17. Xazrcqc表示:

    Привет!
    Купить диплом о среднем образовании в Москве и любом другом городе
    arusak-diploms-srednee.ru/kupit-diplom-magistra В 

  18. The People Who Are Closest To Coffee Beans Machine Share Some
    Big Secrets Automatic bean to cup machine

  19. sex表示:

    I quite like looking through a post that can make people think. Also, thank you for allowing me to comment.

  20. ngentot pepek表示:

    I seriously love your blog.. Pleasant colors & theme. Did you develop this website yourself? Please reply back as I’m hoping to create my own personal site and would love to learn where you got this from or what the theme is called. Cheers.

  21. Dnrtdln表示:

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

  22. Can Financial Modification Assist A Sub-Prime Loan? 다바오 lgbt 호텔

  23. Diplomi_ihEa表示:

    Добрый день!
    Заказать документ о получении высшего образования можно у нас.
    asxdiplomik.com/kupit-diplom-voronezh

  24. 3 Reasons You’re Not Getting Cheap Sectional Sofas Isn’t Performing (And The Best
    Ways To Fix It) http://www.4452346.xyz

  25. Responsible For The Double Glazing In High Wycombe Budget?

    Twelve Top Ways To Spend Your Money Window Doctor High
    Wycombe (https://Humanlove.Stream/)

  26. There Is No Doubt That You Require ADHD Diagnosis http://www.9326527.xyz

  27. Your post has sparked a lot of ideas for me.구글상위노출 회사

  28. kontol表示:

    Greetings! Very helpful advice within this article! It is the little changes that make the largest changes. Thanks a lot for sharing!

  29. 257634.xyz表示:

    20 Fun Facts About Windows Repairs Near Me 257634.xyz

發佈留言

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