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

  1. I simply wanted to thank you so much once more. I’m not certain the things I could possibly have created in the absence of the actual smart ideas revealed by you on my situation. It actually was a alarming difficulty for me, however , looking at a professional tactic you dealt with that forced me to cry with gladness. Extremely happy for your service and even wish you really know what an amazing job you were accomplishing training other individuals all through a site. More than likely you haven’t come across any of us.

  2. What’s The Good And Bad About Adult L Shaped Bunk Beds Kids l Shaped bunk beds

  3. There are certainly a number of particulars like that to take into consideration. That is a great level to convey up. I supply the ideas above as normal inspiration but clearly there are questions like the one you deliver up where an important thing will likely be working in honest good faith. I don?t know if finest practices have emerged around issues like that, however I am sure that your job is clearly identified as a fair game. Both boys and girls really feel the affect of only a second’s pleasure, for the rest of their lives. Miss Verlene

  4. 17 Signs To Know If You Work With Private Psychiatrist In London Private Psychiatrist Edinburgh Cost

  5. Bunk Beds Best Buy Tools To Streamline Your Daily Life Bunk Beds Best Buy Trick That
    Every Person Should Be Able To bunk Beds Best buy

  6. El comercio de opciones binarias es una modalidad de trading en la que los inversores predicen si el valor de un activo se mantendra o cambiara. Plataformas como Quotex ofrecen herramientas avanzadas para el trading de opciones binarias. Con conocimientos y herramientas, es posible mejorar las predicciones en el trading de opciones binarias. El comercio de opciones binarias se ha vuelto popular en paises como Mexico y globalmente.
    broker para opciones binarias quotex limited .

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

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

  9. Arthurjen表示:

    Ретрит http://ретриты.рф международное обозначение времяпрепровождения, посвящённого духовной практике. Ретриты бывают уединённые и коллективные; на коллективных чаще всего проводится обучение практике медитации.

  10. Coreyges表示:

    Discover the world of excitement at Pin Up Casino, the world’s leading online casino. The official website Game pic up offers more than 4,000 slot machines. Play online for real money or for free using the working link today

  11. El comercio de opciones binarias es una forma de inversion en la que los inversores calculan si el valor de un activo subira o bajara. Brokers como Quotex ofrecen herramientas avanzadas para el trading de opciones binarias. Utilizando indicadores y analisis, es posible maximizar los beneficios en el trading de opciones binarias. El comercio de opciones binarias se ha vuelto una opcion atractiva en paises como Mexico y globalmente.
    opciones binarias mexico quotex descargar .

  12. VictorTax表示:

    Remember when Lady Gaga ‘bled’ onstage during her shocking performance at the 2009 VMAs?
    гей онлайн

    Singing about the perils of fame, being dragged out from beneath a fallen chandelier then bleeding to death in front of a roomful of celebrities: Lady Gaga was not shy about making her debut at the MTV Video Music Awards.

    The year was 2009 — many will remember it as the year rapper Ye (formerly Kanye West) stage-crashed 19-year-old Taylor Swift and suggested her award for Best Female Video should have gone to Beyonce instead. But never one to be overshadowed, Lady Gaga, then 23, made some pop culture history of her own that night.

    Her rendition of “Paparazzi” — lamenting both unrequited love and the sinister effects of hounding tabloids — has gone down in the mists of Gaga legend; not least because a lack of high-quality footage means fans must resort to watching grainy screen-recorded versions circulated on social media.
    Over the limited number of pixels, Gaga can be seen at the start of the performance in an all-white ensemble: a bejeweled, asymmetric lace bodysuit and matching cape, thigh-high boots, a feathered Keko Hainswheeler headpiece and strings of glinting pearls. As she staggered back from her piano at the song’s crescendo, however, an audible gasp swept the room as thick blood suddenly appeared to be pouring from her abdomen.

    “I’m your biggest fan, I’ll follow you until you love me,” Gaga wailed desperately, her once-pristine outfit now daubed in scarlet. She ended the number suspended above the stage, ‘dead,’ as more blood dripped from her eyes.

    “(It) gives me chills every time I watch it,” Olivia Rodrigo told MTV in 2021. “I think Lady Gaga is the best performer of our generation.” The “Drivers License” singer appeared to take notes. At this year’s Grammy Awards, she began to ‘bleed’ from clenched fists while performing her hit “vampire,” spreading fake blood across her arms and neck as the song progressed.

  13. Bedpage表示:

    I like it when folks get together and share views. Great blog, stick with it!

  14. Eugenesmivy表示:

    Drought-hit Danube River reveals scuttled German World War II ships
    анальный секс зрелых
    The wrecks of explosives-laden Nazi ships sunk in the Danube River during World War II have emerged near Serbia’s river port town of Prahovo, after a drought in July and August that saw the river’s water level drop.

    Four vessels dating from before 1950 have also come to light in Hungary’s Danube-Drava National Park near Mohacs, where the Danube’s water level stood at only 1.5 meters (4.9 feet) on Tuesday, the lingering effect of severe heat waves and persistent drought in July and August.

    The vessels revealed in Prahovo were among hundreds scuttled along the Danube by Nazi Germany’s Black Sea fleet in 1944 as they retreated from advancing Soviet forces, destroying the ships themselves. The wrecks can hamper river traffic during low water levels.
    Strewn across the riverbed, some of the ships still have turrets, command bridges, broken masts and twisted hulls, while others lie mostly submerged under sandbanks.

    Endre Sztellik, a guard at the Danube-Drava national park, said of one of the ships, “we still don’t know what this is exactly. What is visible and an unfortunate fact is that the wreck is diminishing as people are interested in it and parts of it are going missing.”
    The Danube stood at 1.17 meters (3.8 feet) in Budapest on Tuesday, which compares with an all-time record low of around 0.4 meters (1.3 feet) registered in October 2018. During floods, the Danube rises well above 6 meters (19.7 feet).

    “Eastern Europe is experiencing critical drought conditions that are affecting crops and vegetation,” the European climate service Copernicus said on its website in its latest drought report, published earlier this month.

  15. Titration ADHD Meds Tools To Make Your Daily Lifethe One Titration ADHD Meds Trick That Everyone Should Know titration adhd Meds (http://ns1.javset.net)

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

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

  18. www.i-hire.ca表示:

    5 Double Glazing Birmingham Projects For Any Budget
    rapid rise doors repair birmingham (http://www.i-hire.ca)

  19. Bedpage表示:

    There is certainly a great deal to find out about this topic. I like all of the points you made.

  20. AntnPaish表示:

    First Name: Email Address: Welcome Message Learn more about this site in a welcome video from Dr.
    Legitimate Internet privacies provide a convenient way to buy lasix vs.hydrochlorothiazide at competitive prices when you purchase from known online
    Home Health Information Mouth Oral Cancer Mouth Oral Cancer 532 Users are discussing this topic Article Related Support Clinical Trials Discuss Print PDF Email Bookmark Bookmarked Remove?

  21. 9710861.xyz表示:

    Wall Mounted Oil Filled Radiator 101: This Is The Ultimate
    Guide For Beginners 9710861.xyz

  22. Bedpage表示:

    There’s certainly a lot to learn about this topic. I really like all of the points you have made.

  23. Five Things You Didn’t Know About Assessment For Adhd In Adults
    should I get assessed for adhd

  24. Eanrscy表示:

    Привет!
    Мы готовы предложить дипломы психологов, юристов, экономистов и прочих профессий по приятным тарифам.
    ivyfoods.co.uk/product/?category=Non+Basmati+rice&product=Sona+Masoori++Rice

  25. ArchieWaize表示:

    Pin up casino official Slot pick up casino website – login and play online

發佈留言

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