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); //排序後:法国话,京片子,英语,中国,中文
engineer resume template https://resume-engineering-builder.com
Приобретение школьного аттестата с официальным упрощенным обучением в Москве
Great articles and great layout. Your blog post deserves all of the positive feedback it’s been getting.
Step by step typically the body of drinking water gets improved, generally the home loan loan providers recede, normally the fishing holes run further more silently, to not point out in the conclusion, with no the have to have for exposed ruin, numerous turned out to become merged in your underwater, to not point out painnessly eliminate his or her’s certain ever more staying.
Interesting article. Where did you got all the information from…
Aw, it was a really good post. In concept I have to place in writing like this moreover – spending time and actual effort to produce a very good article… but what can I say… I procrastinate alot and also by no means manage to get something completed.
I simply wanted to thank you so much once more. I’m not certain the things I could possibly have created in the absence of the actual smart ideas revealed by you on my situation. It actually was a alarming difficulty for me, however , looking at a professional tactic you dealt with that forced me to cry with gladness. Extremely happy for your service and even wish you really know what an amazing job you were accomplishing training other individuals all through a site. More than likely you haven’t come across any of us.
Компания relocate-group помогает по получению гражданства Португалии. Кроме того, мы предлагаем визы в США, Канаду, Англию, ЕС и поддержку в эмиграции. Наши специалисты предлагаем индивидуальный подход на всех этапах релокации.
В Релокейт-Групп мы понимаем, как важна поддержка в процессе переезда в другую страну. Наша команда готовы ответить на ваши вопросы и оказать поддержку на каждом этапе переезда. Мы гарантируем, что с нами вы добьетесь необходимых документов.
i love the Bazooka of Megatron, i don’t understand why they did not include it on the movie`
интернет заработок интернет заработок .
It’s good to see this information in your post, i was looking the same but there was not any proper resource, thanx now i have the link which i was looking for my research.
Если вы искали где отремонтировать сломаную технику, обратите внимание – профи новосибирск
ремонт телефонов в москве адреса
вывод из запоя самара стационар http://vyvod-iz-zapoya-v-stacionare-samara11.ru/ .
Профессиональный сервисный центр по ремонту Apple iPhone в Москве.
Мы предлагаем: качественный ремонт айфонов в москве
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
download instagram stories download instagram stories .
Привет, друзья!
Мы изготавливаем дипломы психологов, юристов, экономистов и прочих профессий по приятным ценам.
synfig.org/issues/thebuggenie/synfig/issues/7925
I love your blog.. very nice colors & theme. Did you create this website yourself or did you hire someone to do it for you? Plz answer back as I’m looking to create my own blog and would like to know where u got this from. thanks
I wanted to say Appreciate providing these details, youre doing a great job with the site…
My brother recommended I might like this web site. He was entirely right. This post truly made my day. You can not imagine simply how much time I had spent for this information! Thanks!
It’s difficult to find knowledgeable people within this topic, but you sound like there’s more you’re speaking about! Thanks
I am extremely impressed together with your writing abilities and also with the layout in your weblog. Is this a paid subject matter or did you customize it yourself? Either way keep up the excellent high quality writing, it’s rare to peer a great blog like this one these days..
As far as me being a member here, I didnt even know that I was a member here. When the article was published I received a notification, so that I could participate in Comments, so perhaps that is it. But we’re certainly all members in the world of ideas.
Oh my goodness! an incredible article dude. Thanks a ton However My business is experiencing problem with ur rss . Do not know why Not able to subscribe to it. Can there be everyone obtaining identical rss dilemma? Anyone who knows kindly respond. Thnkx
вывод из запоя самара стационар https://www.vyvod-iz-zapoya-v-stacionare-samara11.ru .
watch stories watch stories .
You made some decent points there. I looked on-line for the issue and located most people should go along with along with your internet site.
fantastic submit, very informative. I ponder why the opposite experts of this sector do not understand this. You must proceed your writing. I’m sure, you have a great readers’ base already!
I really believe, your opinions must be intelligent, each and every premise will have to be nimble to get directed next to a person on your behalf.
Aw, this became an exceptionally nice post. In thought I have to place in writing like this additionally – spending time and actual effort to make a good article… but exactly what can I say… I procrastinate alot and by no means often go carried out.