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); //排序後:法国话,京片子,英语,中国,中文
Можно ли купить аттестат о среднем образовании? Основные рекомендации
laviehub.com/blog/kupit-diplom-506072cfry
Hello! I just wish to give you a big thumbs up for the great info you have here on this post. I will be returning to your website for more soon.
15 Shocking Facts About Lamborghini Diablo Key You Didn’t Know
cheapest
You’ll Never Be Able To Figure Out This Renault Kadjar Replacement Key’s Benefits renault kadjar replacement key
Профессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
Мы предлагаем: сервис центры бытовой техники пермь
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
Быстрая схема покупки диплома старого образца: что важно знать?
Риобет
Как официально купить аттестат 11 класса с упрощенным обучением в Москве
erudio.global/blog/index.php?entryid=36689
Responsible For A Private Psychiatrist Cardiff Budget?
10 Unfortunate Ways To Spend Your Money Private Psychiatrists Northern Ireland
The No. 1 Question That Anyone Working In Glass Replacement Should
Know How To Answer window glass replacements near me (https://writerauthor15.bravejournal.net/20-insightful-quotes-about-replacement-glass-for-windows)
Риобет
You’ll Be Unable To Guess Upvc Door Locks’s Tricks Lock upvc Door
Мы гордимся тем, что можем предложить своим клиентам оперативную помощь в получении микрозаймов на самых выгодных условиях. Наши специалисты всегда готовы оказать консультационную поддержку и помочь вам выбрать наиболее подходящий вариант кредитования.
микрозаймы онлайн микро займы .
вывод из запоя на дому ростов-на-дону вывод из запоя на дому ростов-на-дону .
sykaaa
Профессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
Мы предлагаем: сервисные центры по ремонту техники в перми
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
Tips To Have A Fun Hen Party In Dublin 제주오피 (https://click4r.com/)
Riobet
Покупка диплома о среднем полном образовании: как избежать мошенничества?
The mysterious symbols found carved in Qatar’s desert
пидар
Some shoot out of the soft rock like reptiles bathing in the sun. Others are mysterious depressions resembling an ancient board game played all over the world. And a few are straight-up puzzling.
On a desolate and windswept corner of Qatar’s northeastern coast, among the sand dunes of the barren desert, lies Al Jassasiya, the Gulf country’s largest and most important rock art site.
Here, people centuries ago used a series of low-lying limestone outcrops as a canvas on which they carved symbols, motifs and objects that they observed in their environment.
Overall, archaeologists have found a total of some 900 rock carvings, or “petroglyphs,” at Al Jassasiya. They are mostly enigmatic cup marks arranged in various patterns, including rows and rosettes, but also eye-catching representations of sailing ships, usually seen from above but also depicted in linear profile, among other symbols and signs.
“Although rock art is common in the Arabian Peninsula, some of the carvings in Al Jassasiya are unique and cannot be found anywhere else,” Ferhan Sakal, head of excavation and site management at Qatar Museums, told CNN, referring to the petroglyphs of ships seen from a bird’s-eye view.
“These carvings represent a high degree of creativity and observation skills the part of] the artists who made them,” he said. “Also abstract thinking, as they were not able to see the dhow (a traditional ship) from above.”
Благодаря нашему многолетнему опыту работы в сфере микрофинансирования, мы знаем, какие решения лучше всего подходят для различных жизненных ситуаций. Мы предлагаем широкий выбор кредитных продуктов, которые удовлетворяют самые разные потребности наших клиентов, от краткосрочных займов до долгосрочного финансирования с гибкими условиями возврата.
займы займ .
A Look At The Secrets Of Mercedes Spare Key Cost Car Key Cutting And Programming
Responsible For The Bmw Replacement Key Budget? 10 Unfortunate Ways To Spend Your Money Repair
A giant meteorite boiled the oceans 3.2 billion years ago. Scientists say it was a ‘fertilizer bomb’ for life
гей порно член
A massive space rock, estimated to be the size of four Mount Everests, slammed into Earth more than 3 billion years ago — and the impact could have been unexpectedly beneficial for the earliest forms of life on our planet, according to new research.
Typically, when a large space rock crashes into Earth, the impacts are associated with catastrophic devastation, as in the case of the demise of the dinosaurs 66 million years ago, when a roughly 6.2-mile-wide (10-kilometer) asteroid crashed off the coast of the Yucatan Peninsula in what’s now Mexico.
But Earth was young and a very different place when the S2 meteorite, estimated to have 50 to 200 times more mass than the dinosaur extinction-triggering Chicxulub asteroid, collided with the planet 3.26 billion years ago, according to Nadja Drabon, assistant professor of Earth and planetary sciences at Harvard University. She is also lead author of a new study describing the S2 impact and what followed in its aftermath that published Monday in the journal Proceedings of the National Academy of Sciences.
“No complex life had formed yet, and only single-celled life was present in the form of bacteria and archaea,” Drabon wrote in an email. “The oceans likely contained some life, but not as much as today in part due to a lack of nutrients. Some people even describe the Archean oceans as ‘biological deserts.’ The Archean Earth was a water world with few islands sticking out. It would have been a curious sight, as the oceans were probably green in color from iron-rich deep waters.”
When the S2 meteorite hit, global chaos ensued — but the impact also stirred up ingredients that might have enriched bacterial life, Drabon said. The new findings could change the way scientists understand how Earth and its fledgling life responded to bombardment from space rocks not long after the planet formed.
Процесс получения диплома стоматолога: реально ли это сделать быстро?
satopttorg.ru/forum/user/4962/
Your insights really add depth to this topic.오피
Hello, I would like to subscribe for this website to obtain newest updates, therefore where can i do it please assist.
my blog post: https://Theslotsonline.Mystrikingly.com/
What’s The Current Job Market For Double Glazed Window Repairs Professionals?
Double Glazed Window Repairs – https://Www.Dermandar.Com/User/Celeryrate67/ –
ретро казино зеркало https://retromobil-club.ru .
Как быстро и легально купить аттестат 11 класса в Москве