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

  1. Diplomi_vlEn表示:

    купить диплом о высшем образовании в магнитогорске orik-diploms.ru .

  2. Right here is the right webpage for everyone who wants to find out about this topic. You know so much its almost tough to argue with you (not that I personally would want to…HaHa). You definitely put a new spin on a subject which has been discussed for ages. Wonderful stuff, just wonderful.

  3. After exploring a number of the articles on your web site, I truly appreciate your way of blogging. I bookmarked it to my bookmark webpage list and will be checking back soon. Please check out my website too and tell me how you feel.

  4. DaronAvava表示:

    Ukrainian President Volodymyr Zelensky will meet US President Joe Biden and Vice President Kamala Harris in Washington on Thursday. Leon Neal/Getty Images
    CNN

    Ukrainian President Volodymyr Zelensky’s visit to the White House on Thursday could be his final chance to convince a receptive American president of his country’s war aims.
    [url=https://megaweb-10at.com]megaweb12.com[/url]
    The precise details of the “victory plan” Zelensky plans to present in separate meetings to President Joe Biden and Vice President Kamala Harris are unknown, having been closely held until they are presented to the American leaders.

    But according to people briefed on its broad contours, the plan reflects the Ukrainian leader’s urgent appeals for more immediate help countering Russia’s invasion. Zelensky is also poised to push for long-term security guarantees that could withstand changes in American leadership ahead of what is widely expected to be a close presidential election between Harris and former President Donald Trump.

    The plan, people familiar with it said, acts as Zelensky’s response to growing war weariness even among his staunchest of western allies. It will make the case that Ukraine can still win — and does not need to cede Russian-seized territory for the fighting to end — if enough assistance is rushed in.

    That includes again asking permission to fire Western provided long-range weapons deeper into Russian territory, a line Biden once was loathe to cross but which he’s recently appeared more open to as he has come under growing pressure to relent.

    Even if Biden decides to allow the long-range fires, it’s unclear whether the change in policy would be announced publicly.

    Biden is usually apt to take his time making decisions about providing Ukraine new capabilities. But with November’s election potentially portending a major change in American approach to the war if Trump were to win, Ukrainian officials — and many American ones — believe there is little time to waste.
    mega444z36oh4eugj7karzpyatt7ma6ptq5wjil27sfadl5cgcmim7id.onion
    https://megaweb19at.com
    Trump has claimed he will be able to “settle” the war upon taking office and has suggested he’ll end US support for Kyiv’s war effort.

    “Those cities are gone, they’re gone, and we continue to give billions of dollars to a man who refused to make a deal, Zelensky. There was no deal that he could have made that wouldn’t have been better than the situation you have right now. You have a country that has been obliterated, not possible to be rebuilt,” Trump said during a campaign speech in Mint Hill, North Carolina, on Wednesday.

    Comments like those have lent new weight to Thursday’s Oval Office talks, according to American and European officials, who have described an imperative to surge assistance to Ukraine while Biden is still in office.

    As part of Zelensky’s visit, the US is expected to announce a major new security package, thought it will likely delay the shipping of the equipment due to inventory shortages, CNN previously reported according to two US officials. On Wednesday, the US announced a package of $375 million.

    The president previewed Zelensky’s visit to the White House a day beforehand, declaring on the margins of the United Nations General Assembly his administration was “determined to ensure that Ukraine has what it needs to prevail in fight for survival.”
    [url=https://megaweb16at.com]megaweb10.com[/url]
    “Tomorrow, I will announce a series of actions to accelerate support for Ukraine’s military – but we know Ukraine’s future victory is about more than what happens on the battlefield, it’s also about what Ukrainians do make the most of a free and independent future, which so many have sacrificed so much for,” he said.

  5. Istanbul_hgst表示:

    История и развитие Istanbul International Airport, как все начиналось и что из этого вышло.
    Интересные факты о Istanbul International Airport, о которых вы не знали.
    Особенности проектирования аэропорта, которые невозможно не отметить.
    Планы и развитие Istanbul International Airport, прогнозы и перспективы.
    Что делает аэропорт уникальным, какие услуги понравятся каждому.
    istanbul all airports https://airportistanbulinternational.com/ .

  6. Could Ford Key Fob Replacement Be The Key For
    2022’s Challenges? Ford Key Programing

  7. mostbetnkSi表示:

    Ставки на спорт с выгодными условиями только на Мостбет | Скачайте приложение Мостбет для удобного доступа к ставкам | Регистрируйтесь и начните зарабатывать с Мостбет | Все ставки и азартные игры в одном приложении – Мостбет | Легкий доступ к ставкам на сайте и приложении Мостбет | Ставки и игры с надёжным сервисом – только на Мостбет | Всё для ставок и азартных игр – это Мостбет | Огромный выбор игр и бонусов на Мостбет | Лучшие бонусы и акции на официальном сайте Мостбет, мобильное приложение Mostbet [url=http://mostbetkzcasino.kz/]мобильная версия Мостбет[/url].

  8. Lightweight 3 Wheel Pushchair Tools To Help You Manage
    Your Daily Lifethe One Lightweight 3 Wheel Pushchair Technique Every Person Needs To Know lightweight 3 wheel pushchair

  9. Diplomi_hdEn表示:

    купить диплом в якутске orik-diploms.ru .

  10. JulioWek表示:

    1xbet

  11. Diplomi_hvMl表示:

    купить диплом в тобольске arusak-diploms.ru .

  12. bunk beds usa表示:

    A Trip Back In Time The Conversations People Had About Bunk Bed Store 20 Years Ago bunk beds usa

  13. ScottyNub表示:

    доставка алкоголя в москве круглосуточно на дом https://dostavka-alkogolya-moskva-world-1.ru/

  14. быстрый вывод из запоя в стационаре быстрый вывод из запоя в стационаре .

  15. государственные пансионаты для престарелых государственные пансионаты для престарелых .

  16. Rick表示:

    The 10 Most Terrifying Things About Togel4d Login situs toto togel (Rick)

  17. Private ADHD Assessment: What’s New? No One Is Talking About Private adhd assessment reading

  18. Five Mini Cooper Replacement Keys Lessons From The Professionals mini car Key Replacement

  19. Cazrohg表示:

    Как избежать рисков при покупке диплома колледжа или ВУЗа в России
    erudio.global/blog/index.php?entryid=41443&nonjscomment=1&comment_itemid=41443&comment_context=37836&comment_component=blog&comment_area=format_blog

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

  21. государственный пансионат для престарелых инвалидов государственный пансионат для престарелых инвалидов .

發佈留言

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