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); //排序後:法国话,京片子,英语,中国,中文
its great as your other articles : D, regards for posting .
The fascinating story of the creation and meteoric rise of Amazon https://amazon.jeff-bezos-fr.com from its humble beginnings as an online bookstore to its dominant force in the world of e-commerce.
Some really interesting info , well written and loosely user genial .
leflunomide canada – order generic actonel 35 mg buy cartidin pill
you have a excellent blog here! do you want to develop invite posts in this little weblog?
Good day! I could have sworn I’ve visited this web site before but after going through a few of the articles I realized it’s new to me. Regardless, I’m certainly happy I came across it and I’ll be bookmarking it and checking back often.
I could not refrain from commenting. Very well written!
Olympique de Marseille https://liga1.marseilles-fr.com after several years in the shadows, once again becomes champion of France. How did they do it and what prospects open up for the club
you have a very fantastic blog here! do you wish to have the invite posts on my small weblog?
This site really has all of the info I wanted about this subject and didn’t know who to ask.
The fascinating story of Gigi Hadid’s rise to Victoria’s Secret Angel https://victorias-secret.gigi-hadid-fr.com status and her journey to the top of the modeling industry.
Travel to the pinnacle of French football https://stadede-bordeaux.bordeaux-fr.org at the Stade de Bordeaux, where the passion of the game meets the grandeur of architecture.
Parisian PSG https://paris.psg-fr.com is one of the most successful and ambitious football clubs in Europe. Find out how he became a global football superstar.
“Having read this I thought it was very informative. I appreciate you taking the time and effort to put this article together. I once again find myself spending way to much time both reading and commenting. But so what, it was still worth it!”
Best Keyphrase Research Tips – Few Untapped Keyword
Research Techniques 검색엔진최적화 대행사
Une ascension fulgurante au pouvoir Donald Trump https://usa.donald-trump-fr.com et son empire commercial
Max Verstappen and Red Bull Racing’s https://red-bull-racing.max-verstappen-fr.com path to success in Formula 1. A story of talent, determination and team support leading to a championship title.
The astonishing story of Emmanuel Macron’s https://president-of-france.emmanuel-macron-fr.com political rise from bank director to the highest office in France.
Kim Kardashian’s https://the-kardashians.kim-kardashian-fr.com incredible success story, from sex scandal to pop culture icon and billion-dollar fortune.
Pretty! This was an extremely wonderful post. Many thanks for providing this info.
Aw, this was an incredibly nice post. Finding the time and actual effort to produce a good article… but what can I say… I put things off a whole lot and don’t manage to get nearly anything done.
Things To Take Into Consideration Before You Employ A Car Loan 저신용자 대출
The fascinating story of the creation and rapid growth of Facebook https://facebook.mark-zuckerberg-fr.biz under the leadership of Mark Zuckerberg, who became one of the most influential technology entrepreneurs of our time.
The legendary boxing world champion Mike Tyson https://ufc.mike-tyson-fr.biz made an unexpected transition to the UFC in 2024, where he rose to the top, becoming the oldest heavyweight champion.
The fascinating story of how Lewis Hamilton https://mercedes.lewis-hamilton-fr.biz became a seven-time Formula 1 world champion after signing with Mercedes.
The story of Fernando Alonso https://formula-1.fernando-alonso-fr.com in Formula 1: a unique path to success through talent, tenacity and strategic decisions, inspiring and exciting.
The powerful story of Conor McGregor’s https://ufc.conor-mcgregor-fr.biz rise to a two-division UFC championship that forever changed the landscape of mixed martial arts.
Привет!
Мы изготавливаем дипломы любой профессии по разумным тарифам.
Мы можем предложить документы ВУЗов, расположенных в любом регионе России. Можно купить диплом за любой год, указав актуальную специальность и оценки за все дисциплины. Документы печатаются на “правильной” бумаге самого высокого качества. Это дает возможность делать настоящие дипломы, которые невозможно отличить от оригиналов. Они заверяются необходимыми печатями и штампами.
Даем гарантию, что при проверке документов работодателями, никаких подозрений не возникнет.
Где купить диплом специалиста?
elfae.ruhelp.com/viewtopic.php?id=6925#p25970
Добрый день!
Заказать диплом ВУЗа.
Мы предлагаем заказать диплом в отличном качестве, неотличимый от оригинального документа без использования дорогостоящего оборудования и квалифицированного специалиста.
Где купить диплом по необходимой специальности?
http://domovou.3nx.ru/login.php?redirect=posting.php&mode=newtopic&f=23
Успешной учебы!
Howdy! This post couldn’t be written much better! Going through this post reminds me of my previous roommate! He continually kept preaching about this. I will send this information to him. Pretty sure he’ll have a good read. Thank you for sharing!