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

8,953 Responses

  1. Hello there! This post could not be written any better! Looking through this article reminds me of my previous roommate! He always kept talking about this. I will send this post to him. Pretty sure he’s going to have a good read. Thank you for sharing!

  2. Eugeneaftek表示:

    Tiny shards of plastic are increasingly infiltrating our brains, study says
    домашний анальный секс
    Human brain samples collected at autopsy in early 2024 contained more tiny shards of plastic than samples collected eight years prior, according to a preprint posted online in May. A preprint is a study which has not yet been peer-reviewed and published in a journal.

    “The concentrations we saw in the brain tissue of normal individuals, who had an average age of around 45 or 50 years old, were 4,800 micrograms per gram, or 0.5% by weight,” said lead study author Matthew Campen, a regents’ professor of pharmaceutical sciences at the University of New Mexico in Albuquerque.
    “Compared to autopsy brain samples from 2016, that’s about 50% higher,” Campen said. “That would mean that our brains today are 99.5% brain and the rest is plastic.”

    That increase, however, only shows exposure and does not provide information about brain damage, said Phoebe Stapleton, an associate professor of pharmacology and toxicology at Rutgers University in Piscataway, New Jersey, who was not involved in the preprint.

    “It is unclear if, in life, these particles are fluid, entering and leaving the brain, or if they collect in neurological tissues and promote disease,” she said in an email. “Further research is needed to understand how the particles may be interacting with the cells and if this has a toxicological consequence.”

    The brain samples contained 7% to 30% more tiny shards of plastic than samples from the cadavers’ kidneys and liver, according to the preprint.

    “Studies have found these plastics in the human heart, the great blood vessels, the lungs, the liver, the testes, the gastrointestinal tract and the placenta,” said pediatrician and biology professor Dr. Philip Landrigan, director of the Program for Global Public Health and the Common Good and the Global Observatory on Planetary Health at Boston College.

    “It’s important not to scare the hell out of people, because the science in this space is still evolving, and nobody in the year 2024 is going to live without plastic,” said Landrigan, who was not involved with the preprint.

  3. Hi there! I could have sworn I’ve visited this web site before but after browsing through a few of the articles I realized it’s new to me. Anyways, I’m definitely happy I discovered it and I’ll be bookmarking it and checking back frequently!

  4. лечение наркозависимости в стационаре лечение наркозависимости в стационаре .

  5. Trefiex表示:

    Привет!
    Как правильно купить диплом колледжа и пту в России, подводные камни
    mebelnyvkus.ru/kuhnja/kuxonnye-stulya/stul-ccpe-m
    Поможем вам всегда!.

  6. Massage For Strains And Sprains 인천밤문화 (http://www.goformore.ca)

  7. 1xbet_uoEt表示:

    1xbet: ваш билет к крупным выигрышам, бонусы и акции 1xbet: уникальные предложения для игроков, 1xbet: надежный букмекер для всех, 1xbet – ваша уверенность в каждой ставке, 1xbet – это мир возможностей для ставок, 1xbet предоставляет доступ к самым интересным событиям и матчам, 1xbet: профессиональное обслуживание и круглосуточная поддержка, 1xbet: лучшие коэффициенты и высокие шансы на победу, 1xbet – это шанс изменить свою жизнь, 1xbet: ваш надежный партнер в мире ставок, 1xbet: удобный интерфейс и простая навигация, 1xbet – легендарный букмекер с безупречной репутацией, 1xbet: лучший выбор для ставок на любимые команды, 1xbet обеспечивает полную конфиденциальность и безопасность ваших данных, 1xbet: самые актуальные ставки на спорт и киберспорт, 1xbet признан мировым лидером в сфере онлайн-ставок, 1xbet – это современные стандарты и технологии в ставках, 1xbet гарантирует высокий уровень сервиса и профессионализм в каждой ставке.
    1xbet t https://1xbetappdownloadegypt.com/ .

  8. вывод из запоя в стационаре воронежа http://vyvod-iz-zapoya-v-stacionare-voronezh11.ru/ .

  9. Eanrqeb表示:

    Добрый день!
    Мы изготавливаем дипломы любых профессий по приятным ценам.
    hokutosite.com/bbs/yybbs.cgi?pg=60

  10. Mazrptd表示:

    Здравствуйте!
    Пошаговая инструкция по официальной покупке диплома о высшем образовании
    visix.co.uk

  11. вывод из запоя круглосуточно краснодар на дому вывод из запоя круглосуточно краснодар на дому .

  12. google spam表示:

    Aw, this was an exceptionally nice post. Finding the time and actual effort to produce a good article… but what can I say… I put things off a lot and don’t seem to get nearly anything done.

  13. вывод из запоя в стационаре воронежа http://www.vyvod-iz-zapoya-v-stacionare-voronezh11.ru .

  14. WilliamDeeli表示:

    Здравствуйте!
    Мы изготавливаем дипломы.
    ratingforex.ru/forum-forex/viewtopic.php?f=18&t=32492&sid=21c7b064d8c426a02f14a9f44dbc71d3

  15. вывод из запоя стационар (для вывода из запоя в стационаре) вывод из запоя стационар (для вывода из запоя в стационаре) .

  16. вывод из запоя стационар (для вывода из запоя в стационаре) вывод из запоя стационар (для вывода из запоя в стационаре) .

  17. bad medical表示:

    I want to to thank you for this very good read!! I absolutely enjoyed every little bit of it. I’ve got you bookmarked to check out new things you post…

  18. Sazrdpd表示:

    Здравствуйте!
    Диплом о высшем образовании
    telegra.ph/kupit-diplom-ehlektrika-08-22-3

  19. Diplomi_siEa表示:

    Привет!
    Приобрести документ института можно в нашем сервисе.
    intextv.by/forum/user/63885

  20. bad medical表示:

    You need to take part in a contest for one of the highest quality blogs online. I am going to recommend this blog!

  21. I appreciate the effort you’ve put into this.프라그마틱

  22. Greetings! Very helpful advice within this article! It’s the little changes that will make the largest changes. Many thanks for sharing!

  23. лечение наркозависимости в стационаре лечение наркозависимости в стационаре .

發佈留言

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