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

  1. After looking at a few of the blog posts on your website, I seriously appreciate your way of writing a blog. I bookmarked it to my bookmark site list and will be checking back soon. Take a look at my website too and let me know what you think.

  2. Antonethuth表示:

    End of an era: The big change coming to European travel in November
    вебкам модель работа новосибирск

    In travel news this week: an accidental megadeal on first-class tickets, the world’s best-connected airport and why now is a good time to plan a trip to Europe. Plus a bit of relief for those of you traveling this Labor Day weekend.

    Goodbye to EU passport stamps
    Paper mementoes of our travels, from boarding cards to even passports themselves, are fast moving into obsolescence.

    The inky, smudgy joy of a fresh passport stamp will be a thing of the past for visitors to the 29 countries of the European Union Schengen Area starting November 10. That’s when the new automated Entry/Exit System (EES) comes into effect.

    It’s separate from the delayed ETIAS visa waiver program, which is due to start in the first half of 2025 and will mean travelers from outside the EU will be charged a €7 entry fee that is valid for three years.

    Destination inspiration
    Get your stamps while you can with these European vacation picks.

    Il dolce far niente – “the sweetness of doing nothing” – has been perfected by Italians on their vacations in southern sweet spots such as Naples, Ischia, Puglia, the Amalfi Coast and Capri. These remarkable photographs by UK photographer Lucy Laucht show how to relax the Italian way.

    In Hungary, the Gresham Palace is the grandest Budapest hotel of them all, having sat in its prime position overlooking the River Danube for more than a century. Here’s how this architectural gem looks in its current incarnation.

    Finally, if you’re considering a longer stay, an idyllic Swedish town is selling off land with prices so low you might think they’re mistakes. But Gotene, 320 kilometers (200 miles) southwest of Stockholm, is indeed selling plots with prices starting at just 1 krona, or 9 US cents, per square meter (11 square feet).

    Aviation news
    An airline accidentally offered a megadeal on first-class tickets, with 300 lucky customers getting savings of 85% off. Here’s what happened next.

    The staff at Australian flag carrier Qantas must have been flat-out like a lizard drinking sorting that mess out. And if you don’t understand that lingo, it’s time to check out our guide to Aussie slang.

    An airport on the edge of southeast Europe has been named the best connected in the world, with more than 300 direct flights to unique destinations. It’s been networking fast, too; it only opened in 2018.

  3. 5 Tools That Everyone In The Best Accident Lawyer Near Me Industry Should Be Making Use Of Injury Attorney Philadelphia

  4. вывод из запоя в стационаре анонимно вывод из запоя в стационаре анонимно .

  5. Mazrovz表示:

    Привет, друзья!
    Легальная покупка диплома о среднем образовании в Москве и регионах
    testowik.ru/index.php/forum/user/53710-ilelyqaq

  6. Having read this I thought it was extremely enlightening. I appreciate you spending some time and energy to put this content together. I once again find myself personally spending a significant amount of time both reading and commenting. But so what, it was still worth it!

  7. JasonHes表示:

    This city is developing the world’s tallest timber tower, again
    работа для девушек сургут
    The US city of Milwaukee is already home to the world’s tallest timber tower. But another, even taller, wooden skyscraper could be added to its skyline, designed by Vancouver-based studio Michael Green Architects (MGA).

    The firm recently released plans for the development, which includes a 55-story tower made principally from mass timber — thick, compressed, multilayered panels of solid wood. If built, it would usurp the current world title holder, the 25-story Ascent tower by Korb + Associates Architects, as well as becoming the tallest building in the state of Wisconsin.

    MGA, which specializes in wooden architecture, hopes that the project will set a “new global benchmark for mass timber construction.”

    The project is part of the redevelopment of the Marcus Performing Arts Center, which opened in 1969 and won the Honor Award for Excellence in Architectural Design from the American Institute of Architects in 1970. Led by Neutral, which bills itself as a “regenerative development company,” the redesign will transform what is currently the center’s concrete parking lot into a space with residential units, offices, restaurants, cafes, grocery stores and public plazas. According to MGA, construction will cost an estimated $700 million. The plan is currently going through the city’s approval process, during which it is expected to evolve.

    Why timber?
    While the use of mass timber is steadily increasing worldwide, thanks to changes in building regulations and shifting attitudes towards the material, it has yet to match the sheer height of buildings made of concrete and steel — although a slew of timber high-rises have been proposed in recent years. MGA says its tower design would be approximately 600 feet (182 meters) tall — more than double the 284 feet (87 meter) tall Ascent tower.

    “The race for height is important,” said Michael Green, an architect and founder of MGA. “It’s not about showing off, it’s about showing what’s possible to the public.”

    He argued that the reason timber skyscrapers haven’t yet become mainstream is because climate change hasn’t been at the center of the conversation. “We didn’t really need to challenge the status quo of steel and concrete,” he said. “But because those materials are so hard on the climate, we had to find a different way to build towers and big buildings in general.”

  8. Kinnze表示:

    cheap voltaren – buy generic aspirin for sale buy aspirin 75 mg online cheap

  9. вывод из запоя в стационаре анонимно вывод из запоя в стационаре анонимно .

  10. Why You Should Focus On Improving Train Derailment Attorney Accident Injury Lawyers

  11. toto4d表示:

    Five Killer Quora Answers To Toto4d toto4d

  12. Crebig.Com表示:

    What You Should Be Focusing On Improving Coffee Machine For Beans Best Bean To Cup Coffee Machine Usa (Crebig.Com)

  13. Diplomi_cqEa表示:

    Здравствуйте!
    Купить документ о получении высшего образования вы сможете у нас в столице.
    in-ku.net/member.php?u=122739

  14. AngdPaish表示:

    In my case, the physical symptoms of blood clot in leg symptoms were not apparent.
    Don’t wait in long lines, get a cephalexin expired . Find out how it affects you.
    Interestingly, pregnant women may also experience other symptoms not often seen in adults with appendicitis, including uterus contractions, urination that’s painful or difficult, and pain in the upper right belly, possibly as a result of the appendix changing its position during pregnancy.

  15. JoeGed表示:

    Где взять промокод Фонбет fonbet промокод
    Для получения промокода Фонбет, рекомендуется проверять обновления на официальном сайте букмекера, подписаться на рассылку новостей или следить за акциями в социальных сетях. Промокоды также могут быть доступны через партнерские сайты и рекламные кампании. Примером промокода может быть ‘GIFT200’, который предоставляет бесплатные ставки и другие бонусы.

  16. Cazraiu表示:

    Купить диплом о среднем образовании в Москве и любом другом городе

    uralshooter.ru/wp-content/pages/?kak_kupit_diplom_s_garantiey_provodki_bez_riska

  17. bobres-iptv表示:

    When I originally left a comment I appear to have clicked the -Notify me when new comments are added- checkbox and now each time a comment is added I recieve four emails with the same comment. Is there a means you can remove me from that service? Thank you.

  18. bobres-iptv表示:

    After I initially left a comment I seem to have clicked on the -Notify me when new comments are added- checkbox and from now on every time a comment is added I recieve four emails with the exact same comment. Perhaps there is an easy method you are able to remove me from that service? Thanks a lot.

  19. bobres-iptv表示:

    An impressive share! I have just forwarded this onto a friend who had been conducting a little research on this. And he in fact bought me breakfast because I found it for him… lol. So allow me to reword this…. Thank YOU for the meal!! But yeah, thanx for spending time to talk about this subject here on your website.

  20. Fzzdes表示:

    buy colospa for sale – buy arcoxia 120mg online cilostazol online order

  21. Lazrqfg表示:

    Здравствуйте!
    Мы можем предложить дипломы любой профессии по приятным ценам.
    lada-xray.net/member.php?u=24841

  22. наркология вывод из запоя в стационаре https://www.vyvod-iz-zapoya-sochi11.ru .

發佈留言

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