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); //排序後:法国话,京片子,英语,中国,中文
https://abc-context.ru/
Nice post. I find out some thing tougher on different blogs everyday. Most commonly it is stimulating to study content from other writers and employ something from their site. I’d choose to apply certain together with the content in this little weblog no matter whether you do not mind. Natually I’ll give you a link on your web blog. Thank you for sharing.
Надежный поставщик динамических и статических прокси, сохраняющий стабильность вашей web активности: резидент прокси – https://residential-proxy.ru/
There are some interesting cut-off dates on this article but I don know if I see all of them center to heart. There is some validity however I will take maintain opinion until I look into it further. Good article , thanks and we want extra! Added to FeedBurner as effectively
Hello. i can see that you are a really great blogger,
Exactly how did you discover about this? Effectively i have been looking for this problem for a while. Many thanks individual you might be the brand new main character
Преимущества перетяжки мягкой мебели, Как выбрать качественную ткань для перетяжки мягкой мебели, Какие стили актуальны в обновлении диванов, Как быстро и недорого освежить диван без перетяжки, Профессиональная перетяжка мягкой мебели: за и против, как избежать ошибок при выборе исполнителя, для создания уютного уголка в доме
перетяжка мягкой мебели https://obivka-divana.ru/ .
https://pokertime.ru/blog/obuchenie/kak-nauchitsya-igrat-v-poker/
Hi! I just want to give you a huge thumbs up for your great information you have here on this post. I’ll be coming back to your website for more soon.
Economic importance
Filing an annual report, even if there is no activity, has several important purposes:
For cryptocurrency companies seeking to operate in Australia, understanding the different types of licences and regulatory requirements is a key aspect of successful adaptation and growth. Australia’s progressive and clear regulation creates a favourable environment for innovation and growth in the cryptocurrency industry, while protecting investors and ensuring the integrity of the financial system. By staying abreast of these requirements and actively engaging with regulators, companies can maximise the opportunities presented by the Australian market.
2,000 EUR
Supplying equipment like automated teller machines, Bitcoin teller machines, or vending machines to facilitate transactions through electronic terminals, thereby promoting virtual asset activities that actively facilitate the exchange of virtual assets with legal tender or other virtual currencies.
It shall have, or has received from the competent supervisory authorities of the receiving State in which the national payment organization intends to provide payment services, information indicating that there are reasonable grounds to suspect that the offense referred to in the article. 165a or article. 299 of the Criminal Code of the Russian Federation, there was an attempt to commit such a crime or the commission of such a crime is intentional, or the initiation of services by a branch or through an agent could increase the risk of money laundering or the financing of terrorism.
The Payment Card Interchange Fee Regulations 2015 (PCIFR) – primarily regulate the interchange fees applied to payment card transactions
Step 2: Developing the business model
Additional information
Our company is dedicated to delivering high quality customer service and legal and accounting expertise across various domains. In the event of disputes arising during the execution of a contract between the customer and Regulated United Europe, both parties will first seek resolution through negotiations whenever possible. Should negotiations fail to bring about a resolution, the parties, following the legally prescribed procedure for judicial dispute resolution, may present the matter to the Vilnius District Court.
Particular paid google internet pages offer complete databases relating whilst personal essentials of persons while range beginning telephone number, civil drive public records, as well as criminal arrest back-ground documents.
The ghost town that has stood empty for more than a century
гей порно
There’s a large and very dignified school in Kayakoy. There are narrow streets, lined with houses, that wend and rise up both sides of a steep valley. There’s an ancient fountain in the middle of the town. And there are churches, one with million-dollar hilltop views over the blue Aegean.
But, for most of the past 100 years, there have been no people.
Kayakoy, in southwestern Turkey’s Mugla Province, is a true ghost town. Abandoned by its occupants and haunted by the past. It’s a monument, frozen in time – a physical reminder of darker times in Turkey.
With hillsides dotted by countless crumbling buildings slowly being swallowed by greenery, and endless views into vanished lives, it’s also a fascinating and starkly beautiful place to visit. In summer, under clear skies and blazing suns, it’s eerie enough. Even more so in cooler seasons, wreathed in mountain or sea mists.
Just over a century ago, Kayakoy, or Levissi as it was known, was a bustling town of at least 10,000 Greek Orthodox Christians, many of whom were craftspeople who lived peacefully alongside the region’s Muslim Turkish farmers. But in the upheaval surrounding Turkey’s emergence as an independent republic, their simple lives were torn apart.
Tensions with neighboring Greece after the Greco-Turk war ended in 1922 led to both countries ejecting people with ties to the other. For Kayakoy, that meant a forced population exchange with Muslim Turks living in Kavala, in what is now the Greek region of Macedonia and Thrace.
But the newly arrived Muslims were reputedly less than happy with their new home, swiftly moving on and leaving Kayakoy to fall to ruin.
Woah! I’m really digging the template/theme of this blog. It’s simple, yet effective. A lot of times it’s challenging to get that “perfect balance” between usability and visual appeal. I must say you’ve done a great job with this. Additionally, the blog loads extremely quick for me on Firefox. Outstanding Blog!
Добрый день!
Купить документ о получении высшего образования можно в нашей компании в столице.
sovetushka.forum2x2.ru/t28199-topic#62837
This is a topic that’s near to my heart… Best wishes! Exactly where are your contact details though?
The way you write, you are really a professional blogger.:”~`:
Привет!
Заказать документ ВУЗа.
Мы изготавливаем дипломы любой профессии по приятным тарифам.
zheldor-city.ru
Рады оказать помощь!.
https://www.gemius.ru/
Здравствуйте!
Приобрести диплом любого университета
uspekhi-fond.ru
Привет!
Диплом любой специальности
2718281828.com/blog/index.php?userid=216935&blogpage=12
Здравствуйте!
Всё, что нужно знать о покупке аттестата о среднем образовании без рисков
genafond.spb.ru/forum/index.php?showtopic=185
What’s The Job Market For Best American Style Fridge Freezer
Professionals Like? American Style Fridge
I really like it whenever people come together and share opinions. Great blog, continue the good work!
Привет!
Как приобрести аттестат о среднем образовании в Москве и других городах
longlive.com/node/1703
Рады оказать помощь!.
Привет!
Официальное получение диплома техникума с упрощенным обучением в Москве
nvkb.ru/forum/index.php/user/102885
продвинуть сайт в москве продвинуть сайт в москве .
Добрый день!
Приобрести документ института можно у нас в столице.
avisotskiy.com/2013/03/autodesk-revit_21
Very good information. Lucky me I recently found your site by chance (stumbleupon). I’ve book marked it for later.
Профессиональный сервисный центр по ремонту ноутбуков, макбуков и другой компьютерной техники.
Мы предлагаем:сервис макбук в москве
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
I’m impressed, I have to admit. Rarely do I come across a blog that’s equally educative and entertaining, and without a doubt, you’ve hit the nail on the head. The problem is something which too few folks are speaking intelligently about. I’m very happy that I found this in my hunt for something concerning this.