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

22,535 Responses

  1. MichaelBiady表示:

    Cute baby animals bring visitors to zoos and aquariums. What happens when they grow up?
    [url=https://t.me/traffictemnik]арбитраж трафика как начать[/url]
    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.

  2. Phillipedugs表示:

    Look of the Week: Kendrick Lamar’s Super Bowl pants signal the return of flares
    [url=https://kra27s.cc]Площадка кракен[/url]
    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.

  3. Kevinalgon表示:

    Scores of unexploded World War II bombs discovered under children’s playground
    [url=https://t.me/Lucky_Jetteam]лаки джет бонус[/url]
    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.

  4. What’s The Current Job Market For Double Glazed
    Repairs Near Me Professionals? double glazed repairs near me

  5. Kevinjef表示:

    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. DavidCooth表示:

    https://preman69.tech/# Slot dengan fitur interaktif semakin banyak tersedia

  7. Aaronbus表示:

    slot 88 slot88.company Kasino mendukung permainan bertanggung jawab

  8. Kennethphink表示:

    Scores of unexploded World War II bombs discovered under children’s playground
    [url=https://t.me/Lucky_Jetteam]lucky jet telegram bot[/url]
    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.

  9. MichaelDromb表示:

    Look of the Week: Kendrick Lamar’s Super Bowl pants signal the return of flares
    [url=https://kra27s.cc]kraken darknet[/url]
    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.

  10. Sonnydip表示:

    В 2025 году вопрос активации Windows 10 останется важным для многих пользователей, стремящихся обеспечить безопасность и стабильность своих устройств. Несмотря на появление новых версий операционной системы, таких как Windows 11, Windows 10 продолжит поддерживаться Microsoft с обновлениями безопасности и функциональности. Ключ активации, представляющий собой уникальную комбинацию символов, позволит подтвердить легальность вашей копии и получать доступ к критически важным обновлениям.
    [url=https://windowscollection.ru]ключ активации windows 10[/url]

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

  12. Williecrady表示:

    Slot menjadi daya tarik utama di kasino http://slot88.company/# Kasino menawarkan pengalaman bermain yang seru

  13. ThomasThype表示:

    Slot dengan tema budaya lokal menarik perhatian: preman69.tech – preman69

  14. Aaronbus表示:

    bonaslot BonaSlot Mesin slot sering diperbarui dengan game baru

  15. DavidCooth表示:

    https://slotdemo.auction/# Beberapa kasino memiliki area khusus untuk slot

  16. 5 Private Mental Health Care Lessons From The Professionals
    online mental health check

  17. Williecrady表示:

    Banyak pemain mencari mesin dengan RTP tinggi https://slot88.company/# Kasino di Indonesia menyediakan hiburan yang beragam

  18. Calvinelese表示:

    подборки фильмов бесплатно подборки фильмов бесплатно

  19. Tilt And Turn Window Hinge Covers Tools To Make Your Daily Life Tilt And Turn Window Hinge Covers Trick Every Individual Should Learn tilt and turn window hinge covers

  20. ThomasThype表示:

    Slot dengan pembayaran tinggi selalu diminati: slot demo gratis – slot demo gratis

  21. Создайте идеальную атмосферу в вашем доме с программируемым электрокарнизом, подходит для любого окна.
    Превратите свой дом в оазис комфорта с программируемым электрокарнизом, позволяет вам наслаждаться каждой минутой.
    Пусть ваш дом всегда выглядит стильно и современно с программируемым электрокарнизом, который позволит вам сохранить энергию.
    Превратите свою спальню в уютное убежище с программируемым электрокарнизом, дарит вам возможность наслаждаться каждой минутой вашего сна.
    Создайте идеальные условия для работы и отдыха с программируемым электрокарнизом, поможет вам сэкономить время и энергию.
    умный электрокарниз xiaomi [url=https://elektrokarniz190.ru/]умный электрокарниз xiaomi[/url] .

  22. DavidCooth表示:

    https://preman69.tech/# Slot dengan bonus putaran gratis sangat populer

  23. Williecrady表示:

    Slot dengan tema budaya lokal menarik perhatian http://bonaslot.site/# Bermain slot bisa menjadi pengalaman sosial

  24. Tresa表示:

    Why Do So Many People Want To Know About Upvc Windows Birmingham?
    local glaziers birmingham (Tresa)

  25. Aaronbus表示:

    garuda888 garuda888 slot Permainan slot bisa dimainkan dengan berbagai taruhan

  26. Rob表示:

    Guide To Upvc Window Repair Near Me: The Intermediate Guide To
    Upvc Window Repair Near Me upvc window repair near me (Rob)

  27. ThomasThype表示:

    Pemain bisa menikmati slot dari kenyamanan rumah: preman69 slot – preman69 slot

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

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