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); //排序後:法国话,京片子,英语,中国,中文
купить средне специальное образование купить средне специальное образование .
Предлагаем услуги профессиональных инженеров офицальной мастерской.
Еслли вы искали ремонт ноутбуков hp в москве, можете посмотреть на сайте: срочный ремонт ноутбуков hp
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
Cialis without a doctor prescription: MaxPillsForMen – Cialis over the counter
Some Of The Most Common Mistakes People Make With Asbestosis
Asbestos Mesothelioma Attorney Mesothelioma Lawsuit
Biezak uzdotie jautajumi
Udens spice – ka ta darbojas?
Udens spice pec butibas ir loti vienkarsa, ta parasti ir polietilena vai metala caurule kura saurbti daudzi mazi caurumi kuriem pa virsu ir ciesi piestiprinats smalks metala vai neilona siets
spice jurmala
Filtracijas siets nodrosina lai caurule ieplust tikai udens, bet pasas smiltis paliek sieta arpuse.
Udens spice tiek ierikota smilsaina grunti un ierikosanas dzilumu izvelas ta, lai filtracijas siets atrastos pietiekosi dzili zem udens limena, bet pasas smiltis ap filtracijas sietu butu irdenas un udens caurlaidosas.
Ari dzilums kada sakas gruntsudens ir loti svarigs normalai udens sukna darbibai. Jo dzilak sakas udens limenis, jo udens suknim bus grutak udeni “vilkt” augsa un tadejadi var kristies udens raziba.
Vai spici var ierikot jebkura vieta?
Ka jau ieprieks teksta minets – ir loti svarigi, lai vieta, kur velaties ierikot spici, butu “atbilstosas” smiltis udens spices ierikosanai. Ja smilts ir graudaina (irdena) un gruntsudens limenis nesakas dzilak par 6m no zemes virsmas, tad spici ierikot nevajadzetu but nekadam problemam. Ja smiltis nav parak liels mala piejaukums, … Lasit vairak
Vai var ticet aderem?
Aderu meklesana tiesi ziemelu tautas valstis ir loti izplatits veids ka “atrast udeni” un paaudzu paaudzes so amatu pielieto vietejie aku raksanas meistari un reizem pat spices ierikosanas meistari apgalvojot ka spej “paredzet” udens atrasanas vietu un dzilumu jeb ta saucamas “pazemes upes”. Ari Latvija netrukst cilveku, kas tic sadam … Lasit vairak
Spices ierikosana vai dzilurbums – kadas ir atskiribas?
Spices ierikosanai, vispirms tas ir Diametrs – Polietilena spicem visizplatitakais diametrs ir 32mm un metala spicem – 40mm (jeb 1 ?”). Udens spici apriko ar virszeme novietojamu udens sukni, jeb ta tauta deveto “hidroforu”. Savukart dzilurbuma diametrs ir sakot no 80mm. Pateicoties lielakam caurules diametram, taja var ievietot iegremdejamo sukni … Lasit vairak
Polietilena spices un metala spices – ar ko tas atskiras?
Polietilena spices ir samera moderns risinajums un tas pirmo reizi Latvija paradijas aptuveni pirms 25 gadiem. To kimiska izturiba ir pielidzinama nerusejosam teraudam – tas neruse, neoksidejas un visa garuma nav nevienas savienojuma vietas, kas padara gaisa piesuksanu caur “izpuvusiem” un valigiem savienojumiem neiespejamu, ka ari krietni atvieglo montazu. Virsu … Lasit vairak
Spices ierikosana ir jasaskano buvvalde?
Spices ierikosana lidz 20 metru dzilumam nav jasaskano buvvalde un par to nav jamaksa “zemes dzilu resursu izmantosanas nodoklis”. Ari spices atrasanas vieta ir pec jusu izveles – to var ierikot pie kaiminu zoga cik vien tuvu velaties, tas var ierikot ieksa telpa, pagraba vai tuvu pamatiem. Udens spices nekadi … Lasit vairak
Spices udens kvalitate.
Spices udens kvalitate ir biezi apspriests temats. Var skist, ka udens no dzilurbuma vienmer bus tiraks un labaks neka no spices un lai iegutu labako udeni ir jaurbj pec iespejas dzilak, bet ne vienmer ta ir. Reizem Riga un Rigas rajona tiesi no samera seklam spicem (lidz 10m dzilumam, kas … Lasit vairak
Предлагаем услуги профессиональных инженеров офицальной мастерской.
Еслли вы искали ремонт macbook pro m3, можете посмотреть на сайте: ремонт macbook pro m3 цены
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
Cialis without a doctor prescription: Tadalafil price – Cheap Cialis
Genuinely appreciated this entry. It offered a lot of valuable insights. Great work on writing this.
Официальное получение диплома техникума с упрощенным обучением в Москве
Предлагаем услуги профессиональных инженеров офицальной мастерской.
Еслли вы искали ремонт ноутбуков acer в москве, можете посмотреть на сайте: ремонт ноутбуков acer адреса
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
buy viagra here Fast Pills For Men cheapest viagra
Возможно ли купить диплом стоматолога, и как это происходит
купить диплом в твери
диплом пту купить
купить аттестат в иваново
сделать загранпаспорт быстро сделать загранпаспорт быстро .
http://fastpillsformen.com/# sildenafil online
загранпаспорт быстро загранпаспорт быстро .
Ethena Fi – Your platform for decentralized financial services
ethena
Invest, exchange, and manage your assets with confidence on Ethena Fi
Discover the power of decentralized finance with Ethena Fi. As the world moves towards decentralized financial solutions, Ethena Fi offers you a platform to explore the limitless possibilities of cryptocurrency investments, exchanges, and asset management.
At Ethena Fi, we believe in empowering individuals to take control of their financial future. Whether you’re an experienced investor or new to the world of cryptocurrencies, our user-friendly platform provides you with the tools and resources you need to succeed.
With Ethena Fi, you can:
Invest in a wide range of cryptocurrencies, including Bitcoin, Ethereum, and more
Exchange digital assets quickly and securely
Manage your portfolio with ease
Access innovative financial products and services
Join thousands of users who have already started their journey to financial freedom with Ethena Fi. Sign up today and experience the future of decentralized finance!
Hi Dear, are you genuinely visiting this web site regularly, if so afterward you will absolutely take pleasant experience.
http://cpaday.com.ua/how-to-fix-headlight-fogging-with-sealant.html
загранпаспорт стоимость [url=http://4dkp.forum24.ru/?1-18-0-00003341-000-0-0-1735286007]загранпаспорт стоимость[/url] .
Introducing the Zircuit Token System
The Zircuit token, a pivotal element in the blockchain landscape, plays a crucial role in enabling efficient transactions and offering enhanced security. Designed for seamless integration into various platforms, it aims to revolutionize the way digital currencies are perceived and utilized.
[url=https://web-zircuit.com]zircuit staking[/url]
Key Advantages of the Zircuit Token
Enhanced Security: Security is a core benefit of utilizing the Zircuit token. By employing advanced cryptographic techniques, it ensures that transactions are secure, safeguarding user data and funds from potential threats.
Scalable Transactions: Zircuit token is engineered for scalability, allowing for a large number of transactions per second. This capability promises efficiency even as user numbers grow, ensuring smooth operations across digital platforms.
Low Transaction Fees: One of the significant advantages of using the Zircuit token is the cost-effectiveness of its transactions. It boasts lower fees compared to traditional financial systems, making it an attractive option for users.
Implementing Zircuit Tokens in Everyday Use
The implementation of Zircuit tokens into daily transactions is designed to be straightforward. Users can manage their tokens seamlessly through dedicated wallets that offer user-friendly interfaces and robust security. Thanks to its decentralized nature, it enables trustless interactions, where intermediaries are reduced, thereby minimizing costs and enhancing speed.
Furthermore, Zircuit tokens offer compatibility with various platforms, allowing users to transact with ease across a plethora of services. This flexibility is crucial for both individuals and businesses looking to integrate blockchain technology into their operations.
In conclusion, the Zircuit token stands as a testament to the evolving nature of digital currencies, offering a secure, scalable, and cost-effective solution for modern financial transactions. As adoption continues to grow, the robustness of the Zircuit token system is likely to play a critical role in shaping the future of digital exchanges.
загранпаспорт срочно загранпаспорт срочно .
загранпаспорт быстро https://cinemania.forum24.ru/?1-15-0-00001690-000-0-0-1735288325/ .
загранпаспорт оформить загранпаспорт оформить .
срочное изготовление загранпаспорта срочное изготовление загранпаспорта .
Welcome to Vertex Protocol: Revolutionizing DeFi Trading
Discover the revolutionary Vertex Protocol, your gateway to the world of decentralized finance (DeFi) trading. As the crypto landscape rapidly evolves, Vertex Protocol stands at the forefront, providing users with unparalleled seamless trading experiences and enhanced liquidity access.
[url=https://vertex-protocol.com]vertex protocol trading[/url]
What Makes Vertex Protocol Stand Out?
Vertex Protocol is more than just a trading platform. It is a designed to empower you with:
Intuitive User Interface: Navigate the complex world of crypto with ease and efficiency.
Advanced Security: Enjoy peace of mind with industry-leading security protocols and safeguarding of your assets.
High Liquidity: Access deep liquidity pools to execute large trades with minimal slippage.
Diverse Asset Options: Explore a wide array of cryptocurrencies and tokens.
Unlock Potential with Vertex’s Features
Leverage the full potential of Vertex Protocol with these standout features:
Decentralized: Trustless and Secure
Trading on Vertex ensures transparency and autonomy, free from third-party control, making it a trustless and secure choice for crypto enthusiasts.
Efficient Trading Engine
Benefit from fast, efficient trade execution supported by state-of-the-art technology that maximizes your trading efficiency.
Community Governance
Be a part of a community-driven , allowing you to have a say in the protocol’s future developments.
Getting Started with Vertex Protocol
Embarking on your DeFi journey with Vertex is straightforward. To get started:
Sign up and create your account.
Securely connect your wallet.
Begin trading and explore diverse assets and liquidity options.
Whether you are a seasoned trader or new to the crypto scene, Vertex Protocol offers the tools and resources you need to succeed.
Join the Vertex Community
Participate in webinars, discussions, and forums to stay informed and connected. The vibrant awaits, offering support and insights to enhance your trading journey.
In conclusion, Vertex Protocol is your ideal partner in navigating the dynamic world of decentralized finance. Start today and experience the future of trading.
срочная наркологическая помощь в москве срочная наркологическая помощь в москве .
наркологическая срочная помощь наркологическая срочная помощь .
вызвать наркологическую помощь вызвать наркологическую помощь .