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

21,202 Responses

  1. tina表示:

    BUY VERIFIED eBAY ACCOUNTS
    $250.00 – $350.00

    Buy Verified eBAY Accounts. Discover our service to purchase verified eBay accounts that are tailored for online success. Every account has been thoroughly checked to ensure reliability and security. Boost your ecommerce journey today with ease and trust. Get your eBay verified account through us and start your journey to a stronger online presence.

    Our Service
    ✮ 100% US/UK Verified eBAY Shop Account
    ✮ Number Verified & Access
    ✮ Email Verified and Access ID/Passport/Driving Licence Verified
    ✮ US SSN Verified Full
    ✮ EIN Verified
    ✮ Check your business details
    ✮ Shop Verified
    ✮ EBAY business account verified
    ✮ Verification of Documents
    ✮ Address Verification
    ✮ Order Now & Receive Your Products Immediately
    ✮ Replacement Guarantee
    ✮ Customer Support Available 24/7
    ✮ Money Back Guarantee

    24/7 Hours Repley Contact
    Email: usasellservice@gmail.com
    Skype: USASELLSERVICE
    Telegram: @usasellservice

  2. tina表示:

    Buy Verified Shopify Accounts
    $250.00 – $450.00

    Buy Verified Shopifi Accounts. Shopify premium accounts that are verified. Our accounts are designed to enhance your business through seamless integration. Start your journey to entrepreneurship today with complete confidence! Quality assured.

    Our Service
    ✮ 100% US/UK Verified Tiktok Shop Account
    ✮ Number Verified & Access
    ✮ Email Verified and Access ID/Passport/Driving Licence Verified
    ✮ US SSN Verified Full
    ✮ EIN Verified
    ✮ Check your business details
    ✮ Shop Verified
    ✮ Tiktok business account verified
    ✮ Verification of Documents
    ✮ Address Verification
    ✮ Order Now & Receive Your Products Immediately
    ✮ Replacement Guarantee
    ✮ Customer Support Available 24/7
    ✮ Money Back Guarantee

    24/7 Hours Repley Contact
    Email: usasellservice@gmail.com
    Skype: USASELLSERVICE
    Telegram: @usasellservice

  3. tina表示:

    Buy Tiktok Shop Accounts
    $450.00 – $600.00

    Buy Tiktok Shop Accounts. Want to increase your online presence? We sell TikTok Shop Accounts! We offer ready-made and verified accounts to increase visibility. Profit from TikTok’s massive audience to grow your business today.

    ✮ 100% US/UK Verified Tiktok Shop Account
    ✮ Number Verified & Access
    ✮ Email Verified and Access ID/Passport/Driving Licence Verified
    ✮ US SSN Verified Full
    ✮ EIN Verified
    ✮ Check your business details
    ✮ Shop Verified
    ✮ Tiktok business account verified
    ✮ Verification of Documents
    ✮ Address Verification
    ✮ Order Now & Receive Your Products Immediately
    ✮ Replacement Guarantee
    ✮ Customer Support Available 24/7
    ✮ Money Back Guarantee

    24/7 Hours Repley Contact
    Email: usasellservice@gmail.com
    Skype: USASELLSERVICE
    Telegram: @usasellservice

  4. Kevinalgon表示:

    Scores of unexploded World War II bombs discovered under children’s playground
    lucky jet зеркало
    Scores of unexploded bombs dating from World War II have been recovered from a children’s playground in northern England after a chance discovery.

    Local officials in the town of Wooler, Northumberland called in bomb disposal experts after workers involved in a planned overhaul of Scotts Play Park found unexploded ordnance, the parish council said in a statement sent to CNN on Monday.

    Two bombs were initially removed by the British Army, the UK Ministry of Defense said in a statement. The parish council was then advised that a full survey of the area was required, according to a council spokesperson.
    Bomb disposal company Brimstone Site Investigation then uncovered 65 10-pound practice bombs and smoke cartridges on the first day of works, with a further 90 practice bombs recovered on the second day.

    The company told CNN that the bombs date from World War II.

    According to the parish council, all of the bombs need to be found and removed before the park can be reopened. It said 174 devices had been found so far.

  5. JordanDob表示:

    Cute baby animals bring visitors to zoos and aquariums. What happens when they grow up?
    арбитраж трафика тимы
    One of the best things that can happen to a zoo or aquarium is for one of their resident animals to go viral.

    Just look at the multi-hour-long lines to see Moo Deng, a pygmy hippo in Thailand who has become an internet sensation following her July 2024 birth. The sassy animal is now a full-on brand, with Khao Kheow Open Zoo selling Moo Deng merchandise and even releasing a single “by” the hippo in multiple languages.

    Meanwhile, Pesto — a baby king penguin who was eating more fish than his parents by the time he was a few weeks old — is also an online celebrity, with human stars like Olivia Rodrigo and Katy Perry stopping by to meet him.

    But what happens when these cute animals become, well, less cute? The Sea Life Melbourne aquarium has already been planning for the next phase of Pesto’s life — and answering questions from the public about his changing appearance.

    It’s normal for king penguins to lose their feathers by the time they’re about a year old and become confident swimmers. As a result, a spokesperson for the aquarium says, guests have started asking why Pesto looks different — or why they can’t find him at all.

    “We are getting a few guests thinking we have moved him off display completely,” says the spokesperson. “Most of the team’s time is spent pointing him out to guests because he looks so different now.”
    The bottom line is that cute baby animals make money.

    Admission tickets are only the beginning. Many zoos and aquariums offer special “behind the scenes” or “zookeeper for a day” packages at much higher prices. At Sea Life Melbourne, standard entry tickets for adults start at $51, while the Penguin Passport — which include a 45-minute tour of the birds’ area and a look at how their food is prepared — is $199.

    The real jackpot, though, is merchandise. Stuffed animals, T-shirts, fridge magnets, keychains, kids’ books and other branded products are a major way for zoos and aquariums to make money.

  6. Phillipedugs表示:

    Look of the Week: Kendrick Lamar’s Super Bowl pants signal the return of flares
    кракен ссылка
    This year’s Super Bowl halftime show was hardly a fashion extravaganza, with headliner Kendrick Lamar keeping things simple in a backwards cap and motorbike-style varsity jacket, which he kept on throughout.

    And without the costume-change roulette we’ve come to expect of halftime shows, the internet fixated on one item in particular: his jeans.

    While not quite the bell-bottoms of decades past (the 1970s and the 2000s, specifically), the Compton-born rapper’s washed denim pants flared out at the knee and dragged beneath his heels along the stage at Caesars Superdrome in New Orleans. His silhouette stood in stark contrast to that of record producer Mustard, who made a brief cameo in a pair of outsized jeans straight from the West Coast hip-hop playbook.
    Opinions were, as ever, divided on social media. Some users described Lamar’s flares as “women’s jeans” and “Hannah Montana pants,” earning him comparisons to everyone from Jennifer Aniston to country singer Lainey Wilson. Others joked that their moms were looking for a similar pair or that they nodded to millennials, for whom flares were a teenage staple.

    But those suggesting his style was outdated, or gender-inappropriate, may not have been paying attention to the recent resurgence of flares — in both womenswear and menswear. After all, Lamar’s jeans were designed by one of the most influential figures in modern fashion, Celine’s former creative director Hedi Slimane, before he departed the French label in October.

  7. ThomasThype表示:

    Slot menawarkan kesenangan yang mudah diakses: bonaslot – bonaslot

  8. Gasoline cells of this form operate at very excessive temperatures (between seven-hundred and 1,000 degrees Celsius).

  9. An additional 16,428 cases and 22 deaths were reported.

  10. Williecrady表示:

    Kasino memiliki suasana yang energik dan menyenangkan https://slotdemo.auction/# Mesin slot menawarkan berbagai tema menarik

  11. To this Dr. Franklin responds, “As that title may recommend, sir, we’re not in contact at the present time.” Later when a brand new congressional delegation from New Jersey arrives, the leader of the delegation, Rev.

  12. Aaronbus表示:

    garuda888.top garuda888 slot Slot menawarkan berbagai jenis permainan bonus

  13. How The 10 Worst Double Glazing Repair Near Me Mistakes Of All Time Could Have Been Prevented double glazing Near Me

  14. Hardly ever does a toy command the large appeal and lasting recognition of the Rubik’s Cube.

  15. The Harrap dictionaries are severe, prime quality references which promote well in bookstores; they don’t seem to be the form of bottom feeders you typically discover repackaged on CD-ROMs.

  16. DavidCooth表示:

    https://slotdemo.auction/# Slot dengan grafis 3D sangat mengesankan

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

  18. Just contact a licensed broker for buying and selling.

  19. I really like and appreciate your blog post. Awesome.

  20. Управляйте своим окружением с помощью программируемого электрокарниза, совместим с любым интерьером.
    Превратите свой дом в оазис комфорта с программируемым электрокарнизом, позволяет вам наслаждаться каждой минутой.
    Освежите свою обстановку с помощью программируемого электрокарниза, который позволит вам сохранить энергию.
    Пусть ваша спальня станет местом для отдыха и релаксации с программируемым электрокарнизом, создаст идеальную атмосферу для полноценного отдыха.
    Регулируйте интенсивность света и тепла с помощью программируемого электрокарниза, поможет вам сэкономить время и энергию.
    электрокарниз для умного дома электрокарниз для умного дома .

  21. Williecrady表示:

    Slot dengan tema budaya lokal menarik perhatian https://slot88.company/# Slot dengan grafis 3D sangat mengesankan

  22. ThomasThype表示:

    Pemain bisa menikmati slot dari kenyamanan rumah: garuda888.top – garuda888.top

  23. Phillipedugs表示:

    Look of the Week: Kendrick Lamar’s Super Bowl pants signal the return of flares
    кракен
    This year’s Super Bowl halftime show was hardly a fashion extravaganza, with headliner Kendrick Lamar keeping things simple in a backwards cap and motorbike-style varsity jacket, which he kept on throughout.

    And without the costume-change roulette we’ve come to expect of halftime shows, the internet fixated on one item in particular: his jeans.

    While not quite the bell-bottoms of decades past (the 1970s and the 2000s, specifically), the Compton-born rapper’s washed denim pants flared out at the knee and dragged beneath his heels along the stage at Caesars Superdrome in New Orleans. His silhouette stood in stark contrast to that of record producer Mustard, who made a brief cameo in a pair of outsized jeans straight from the West Coast hip-hop playbook.
    Opinions were, as ever, divided on social media. Some users described Lamar’s flares as “women’s jeans” and “Hannah Montana pants,” earning him comparisons to everyone from Jennifer Aniston to country singer Lainey Wilson. Others joked that their moms were looking for a similar pair or that they nodded to millennials, for whom flares were a teenage staple.

    But those suggesting his style was outdated, or gender-inappropriate, may not have been paying attention to the recent resurgence of flares — in both womenswear and menswear. After all, Lamar’s jeans were designed by one of the most influential figures in modern fashion, Celine’s former creative director Hedi Slimane, before he departed the French label in October.

  24. ForrestBah表示:

    Cute baby animals bring visitors to zoos and aquariums. What happens when they grow up?
    арбитраж трафика как начать
    One of the best things that can happen to a zoo or aquarium is for one of their resident animals to go viral.

    Just look at the multi-hour-long lines to see Moo Deng, a pygmy hippo in Thailand who has become an internet sensation following her July 2024 birth. The sassy animal is now a full-on brand, with Khao Kheow Open Zoo selling Moo Deng merchandise and even releasing a single “by” the hippo in multiple languages.

    Meanwhile, Pesto — a baby king penguin who was eating more fish than his parents by the time he was a few weeks old — is also an online celebrity, with human stars like Olivia Rodrigo and Katy Perry stopping by to meet him.

    But what happens when these cute animals become, well, less cute? The Sea Life Melbourne aquarium has already been planning for the next phase of Pesto’s life — and answering questions from the public about his changing appearance.

    It’s normal for king penguins to lose their feathers by the time they’re about a year old and become confident swimmers. As a result, a spokesperson for the aquarium says, guests have started asking why Pesto looks different — or why they can’t find him at all.

    “We are getting a few guests thinking we have moved him off display completely,” says the spokesperson. “Most of the team’s time is spent pointing him out to guests because he looks so different now.”
    The bottom line is that cute baby animals make money.

    Admission tickets are only the beginning. Many zoos and aquariums offer special “behind the scenes” or “zookeeper for a day” packages at much higher prices. At Sea Life Melbourne, standard entry tickets for adults start at $51, while the Penguin Passport — which include a 45-minute tour of the birds’ area and a look at how their food is prepared — is $199.

    The real jackpot, though, is merchandise. Stuffed animals, T-shirts, fridge magnets, keychains, kids’ books and other branded products are a major way for zoos and aquariums to make money.

  25. Kevinalgon表示:

    Scores of unexploded World War II bombs discovered under children’s playground
    lucky jet telegram bot
    Scores of unexploded bombs dating from World War II have been recovered from a children’s playground in northern England after a chance discovery.

    Local officials in the town of Wooler, Northumberland called in bomb disposal experts after workers involved in a planned overhaul of Scotts Play Park found unexploded ordnance, the parish council said in a statement sent to CNN on Monday.

    Two bombs were initially removed by the British Army, the UK Ministry of Defense said in a statement. The parish council was then advised that a full survey of the area was required, according to a council spokesperson.
    Bomb disposal company Brimstone Site Investigation then uncovered 65 10-pound practice bombs and smoke cartridges on the first day of works, with a further 90 practice bombs recovered on the second day.

    The company told CNN that the bombs date from World War II.

    According to the parish council, all of the bombs need to be found and removed before the park can be reopened. It said 174 devices had been found so far.

  26. You’ll Be Unable To Guess 2 In 1 Highchair’s Secrets 2 in 1 highchair

  27. It is outlined as the sum of the stability of commerce (items and companies exports minus imports), web income from abroad, and internet current transfers.

  28. Предлагаем услуги профессиональных инженеров офицальной мастерской.
    Еслли вы искали ремонт фотоаппаратов canon в москве, можете посмотреть на сайте: срочный ремонт фотоаппаратов canon
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  29. электрокарниз двухрядный http://elektrokarnizy77.ru .

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

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