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

6,797 Responses

  1. RonaldMah表示:

    Learn about Jayson Tatum’s https://celtics-de-boston.jayson-tatum.com rise from young rookie to key leader of the Boston Celtics in the NBA, his impact on the team and his success on the court.

  2. CharlesCoall表示:

    The Boston Celtics https://celtics-de-boston.bill-russel.com are one of the most successful teams in the history of the National Basketball Association (NBA).

  3. Hiya, I am really glad I’ve found this information. Nowadays bloggers publish only about gossips and net and this is actually irritating. A good blog with interesting content, this is what I need. Thanks for keeping this website, I’ll be visiting it. Do you do newsletters? Cant find it.

  4. Oh my goodness! a fantastic post dude. Many thanks Even so We are experiencing problem with ur rss . Do not know why Cannot sign up for it. Could there be everyone getting identical rss difficulty? Anyone who knows kindly respond. Thnkx

  5. I love it when people come together and share opinions, great blog, keep it up.

  6. I really love the way you discuss this kind of topic.~;’.~

  7. Very nice work with your entry. Many readers may view it in the same light for sure and wholly agree with your idea.

  8. Sguptz表示:

    purchase finax – buy finasteride sale oral uroxatral 10mg

  9. RichardMiz表示:

    Частная платная клиника https://mypsyhealth.ru психиатрии, психологии, психотерапии и наркологии анонимно в Москве.

  10. sprinauto表示:

    Аренда автобуса с водителем в СПб: Ваш надежный выбор.

    Если вам нужно аренда автобуса в Санкт-Петербурге, sprinauto предлагает качественные услуги. Мы предлагаем заказ автобусов в СПб по доступным ценам.

    Автобусные перевозки от sprinauto – это высокий уровень сервиса. Вы можете арендовать автобус для перевозки людей по выгодной цене. Наша компания предоставляет автобусы разной вместимости, подходящие для любых нужд.

    Для тех, кто ищет аренду автобуса в СПб, СпринтурАвто предлагает доступные цены и комфортные условия. Мы обеспечиваем вежливых и квалифицированных водителей, которые сделают вашу поездку приятной и безопасной.

    Не откладывайте на завтра, сделайте заказ автобуса прямо сейчас! Позвоните нам по телефону +78129251575, чтобы получить подробную информацию и заказать автобус. спринтуравто – ваш надежный партнер для перевозки людей в Санкт-Петербурге и за его пределами.

  11. Lazrpnx表示:

    Здравствуйте!
    Заказать диплом о высшем образовании.
    bakinsky-dvorik.ru/club/user/127071/blog/4731/

  12. Useful info. Lucky me I found your web site by chance, and I am stunned why this accident didn’t took place in advance! I bookmarked it.

  13. obviously like your website but you have to test the spelling on several of your posts. Many of them are rife with spelling issues and I find it very troublesome to inform the truth then again I’ll certainly come again again.

  14. EdwardSex表示:

    Deep Fake Nudes undress AI with Undress AI and Deepnude

  15. gemstones are expensive but when you give a ring with gemstone to your girlfriend, she would really like it..

  16. It’s arduous to seek out knowledgeable folks on this matter, however you sound like you realize what you’re speaking about! Thanks

  17. Dnrtrsr表示:

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

  18. I am often to blogging i actually appreciate your site content. The content has truly peaks my interest. I’m going to bookmark your web blog and maintain checking for brand spanking new info.

  19. hi!,I love your writing so much! proportion we be in contact extra about your article on AOL? I require an expert on this space to resolve my problem. May be that’s you! Having a look forward to see you.

  20. Meet One Of The Replacement Saab Key Industry’s Steve Jobs Of The Replacement Saab Key Industry saab keys Replacement

  21. Unsecured Loans-Preferred Choice Of Many 신생아 특례 대출

  22. HarryJaw表示:

    Immerse yourself in the charm of France https://france.life-in-france.net a land of fine cuisine, impressive architecture and picturesque landscapes. An unrivaled lifestyle.

  23. Ronaldfiept表示:

    Rodri https://manchester-city.rodrigo-hernandez.com le maestro du milieu de terrain de Manchester City

  24. Doyledum表示:

    L’histoire epique du FC Barcelone https://espagne.barcelona-fr.com 120 ans de triomphes et de tribulations.

  25. LloydPhaps表示:

    Indibet https://indibeti.in is a premier online casino offering a wide array of games including slots, table games, and live dealer options. Renowned for its user-friendly interface and robust security measures, Indibet ensures a top-notch gaming experience with exciting bonuses and 24/7 customer support.

  26. KennethOrelm表示:

    translation screen capture for windows free screen capture for windows 10

  27. Fantastic post! Are you curious to know how scrcpy improved the top Android gaming phones? If so, a screen mirroring program called Scrcpy enables players to enjoy phone games on a bigger screen with a sharper display and less lag, making for a more engaging gaming experience. Visit the article link above for more information.

  28. Lazrqti表示:

    Привет, друзья!
    Мы предлагаем дипломы психологов, юристов, экономистов и любых других профессий по выгодным тарифам.
    mandiplomiks.ru

  29. Michaeldet表示:

    Свежие новости https://diesel.kyiv.ua автомобильного рынка, новинки автопрома

  30. WilberJet表示:

    The fascinating story of Ja Morant’s https://grizzlies-de-memphis.ja-morant-fr.com meteoric rise, from status from rookie to leader of the Memphis Grizzlies and rising NBA superstar.

發佈留言

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