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); //排序後:法国话,京片子,英语,中国,中文

You may also like...

9,075 Responses

  1. sunwin表示:

    I’d like to thank you for the efforts you’ve put in writing this blog. I am hoping to check out the same high-grade blog posts by you in the future as well. In fact, your creative writing abilities has inspired me to get my own, personal site now 😉

  2. Trefqcs表示:

    Добрый день!
    Процесс получения диплома стоматолога: реально ли это сделать быстро?
    diplomman.ru/kupit-diplom-samara
    Окажем помощь!.

  3. JasonDuece表示:

    Fafabet South Africa
    fafabet login
    Step into the thrilling universe of Fafabet’s casino, a place pulsating with excitement and brimming with opportunities for big wins! Whether you’re a seasoned gambler or a curious newcomer, this review will guide you through the vibrant selection of top-tier games, enticing bonuses, effective strategies, and seamless mobile play. Get ready to transform your gaming experience and discover why Fafabet is the go-to destination for online casino enthusiasts!
    Best Casino Games at Fafabet
    brings the excitement of a real casino directly to your screen, featuring a curated selection of games that cater to both new and seasoned players. The focus on popular games such as roulette, blackjack, and poker ensures a varied and engaging experience, providing options for strategic play, quick wins, and everything in between. This selection is not just about variety; it’s tailored to enhance player engagement and retention. The inclusion of games with different levels of complexity and reward strategies meets the diverse needs and preferences of the global online gambling community, making Fafabet a top choice for live casino enthusiasts.

    Choose Your Game: Online Roulette, Blackjack, Poker
    The heart of Fafabet’s live casino lies in its comprehensive offering of classic games, which are among the most popular and enduring in the gambling world. Let’s focus on the star of the casino floor: Roulette. This game not only attracts players with its simplicity and elegance but also offers various versions to suit different tastes and betting styles.

  4. 5 Reasons Private Psychiatrists In London Is Actually
    A Great Thing private Psychiatry Uk

  5. 14 Questions You Might Be Afraid To Ask About Wall Mounted Fireplace http://Www.0773781.xyz

  6. Glenngow表示:

    Jokabet Casino Espana: analisis completo (2024)
    jokabet casino no deposit bonus
    Introduccion a Jokabet Casino
    Jokabet Casino ha emergido como una de las plataformas de juegos de azar en linea mas populares en Espana en 2024. Este analisis completo tiene como objetivo proporcionar una vision detallada de lo que ofrece este casino, desde su seguridad hasta sus juegos y promociones.

    Jugar en Jokabet Casino: ?Es seguro y confiable?
    Antes de aventurarte en el mundo de Jokabet Casino, es natural preguntarse sobre su seguridad. La plataforma esta licenciada y regulada por autoridades reconocidas, garantizando un entorno de juego seguro y justo para todos sus usuarios.

    Los mejores bonos y promociones de Jokabet Casino
    Bonos de bienvenida
    ofrece generosos bonos de bienvenida para nuevos jugadores, incluyendo dinero extra y giros gratis. Con un bono Jokabet inicial, puedes empezar a explorar todas las oportunidades que este casino ofrece.

    Promociones regulares
    Los jugadores habituales pueden disfrutar de diversas promociones regulares, como bonos de recarga y torneos.

    Programas de fidelidad
    El programa de fidelidad de Jokabet recompensa a los jugadores leales con puntos que pueden canjearse por premios y beneficios exclusivos.

  7. Michaelpoold表示:

    Benefits of mobile application
    pin up app apk
    Today, it is very popular among gambling companies to create mobile applications for the users who use the phone the most. Many users download a pin-up program to take advantage of this program, which is the functionality of the browser version of the gambling platform.
    If you decide to download the Pin-up mobile application, you can use this application. The company’s employees care about the comfort of their users. The program has many fans from the world of gambling. The company has worked hard to develop the program.

    the profit

    intuitive interface;

    attractive design;

    Various sporting events and gambling entertainments;

    high speed of application;

    economical use of Internet traffic;

    Fixed access to the application, unlike the browser version.
    where to download apps for android

    There are several ways to download a pin-up program:

    The download file is downloaded directly from the official website of the virtual gambling company. This is the safest and most reliable method because you do not need to be afraid of scammers when downloading from the site;

    It is also recommended to download programs from third-party sites, but first you need to make sure that it is the original file, as scammers can offer you the wrong file.

    Downloading the file is very fast and simple, even the most inexperienced user can easily install this program. On the official website of the company there are detailed instructions on how to install the file on Android.

  8. BobbyOxymn表示:

    Boost kasiino – ametlik kodulehekulg Eestis: taielik ulevaade
    https://boostcasino-ee.com/
    on Eesti mangurite seas kiiresti populaarsust kogunud. Kaesolevas artiklis vaatleme, miks Boost casino eesti on saavutanud sellise edu, kasitledes selle peamisi funktsioone ja pakutavaid teenuseid, sealhulgas manguvalikuid, boonuseid ja kasutajasobralikku liidest.

    Boostcasino Mangude Ulevaade
    Boost Casino pakub laia valikut ponevaid mange, mis meeldivad igale mangijale, alates algajatest kuni kogenud hasartmangusopradeni. Selles jaotises saate teada, milliseid erinevaid mange Boost Casino pakub, sealhulgas populaarseid manguautomaate ja lauamange, samuti live-kasiino voimalusi, mis pakuvad mangijatele toelist kasiinokogemust mugavalt oma kodus.

    Slotid ja Lauamangud
    Boost Casino’s on esindatud sadu slotimange erinevatelt arendajatelt, nagu NetEnt, Microgaming ja Play’n GO, mis tagab kvaliteetsed graafikad ja sujuva mangukogemuse. Lisaks klassikalistele slotidele leidub laialdaselt lauamange, sealhulgas:

    1. Blackjack: Mitu varianti, nagu klassikaline, Euroopa ja Vegas Strip.
    2. Rulett: Euroopa, Ameerika ja Prantsuse rulett.
    3. Baccarat: Punto Banco ja kiire tempo baccarat.

    Nende mangude RTP (Return to Player) maarad on tavaliselt vaga konkurentsivoimelised, mis tostab mangijate voiduvoimalusi. Boost Casino uuendab regulaarselt oma mangude valikut, pakkudes uusi ja ponevaid variante.

  9. HaroldGon表示:

    ISIS-inspired suspect planned suicide attack at Taylor Swift concert, Austrian authorities say
    1xbet promo code new user
    Police in Austria have questioned three teenagers suspected of plotting a suicide attack at a Taylor Swift show, sparking renewed concerns over the indoctrination of young people online.

    Foreign intelligence agencies helped authorities uncover the alleged scheme, according to the country’s Interior Minister Gerhard Karner. A source familiar told CNN that the US issued a warning to authorities in Vienna.

    Organizers canceled three concerts, which were scheduled to take place in the European capital from Thursday to Saturday. CNN has reached out to Swift’s representatives for comment.

    Investigators unearthed a stockpile of chemicals, explosive devices, detonators and 21,000 euros in counterfeit cash at the home of the main suspect, a 19-year-old ISIS sympathizer who had been radicalized online, according to authorities.
    The young man – who was arrested Wednesday morning in the eastern town of Ternitz – planned to kill himself and “a large number of people,” according to the head of the domestic intelligence agency, Omar Haijawi-Pirchner.

    “He said he intended to carry out an attack using explosives and knives,” Haijawi-Pirchner told reporters in Vienna on Thursday. “His aim was to kill himself and a large number of people during the concert, either today or tomorrow.”

    Two other suspects were detained, aged 17 and 15. The 17-year-old worked for a facilities company that would have provided services at the concert venue. He was near the stadium when he was arrested and had recently broken up with his girlfriend, according to Haijwai-Pirchner.

    Little has been revealed about the 15-year-old. Prosecutors will decide later if he was a witness or directly involved in the alleged plot.

    The three are all Austrian-born with either Turkish, North Macedonian or Croatian backgrounds.

  10. Mazrziw表示:

    Привет, друзья!
    Полезная информация как официально купить диплом о высшем образовании
    rushkadiplomik.ru

  11. Danielreame表示:

    Betfair Casino Espana
    bono casino betfair
    Si estas en la busqueda de un casino online en Espana que ofrezca fiabilidad, podria ser la opcion perfecta. Con licencia y cumpliendo con los mas altos estandares de seguridad, este casino destaca por su variada seleccion de juegos proporcionados por los mas renombrados desarrolladores a nivel mundial. Desde tragamonedas clasicas hasta envolventes juegos de casino en vivo, Betfair Casino se ha convertido en el destino favorito de numerosos jugadores espanoles. Descubre en nuestra resena por que Betfair Casino ha logrado captar la atencion de tantos usuarios y conoce en detalle las caracteristicas que lo hacen destacar en el sector.
    Resena sobre Betfair Casino Espana
    Betfair Casino se ha establecido firmemente en el mercado de juegos de azar espanol como una opcion de confianza para los entusiastas del casino online. Operado por Betfair Casino Limited, este sitio esta acreditado por la Comision de Juegos del Reino Unido y la Autoridad de Juegos de Malta, ofreciendo un ambiente de juego seguro y regulado. A continuacion, te proporcionamos informacion relevante sobre Betfair Casino en Espana.

  12. BobbyClert表示:

    Baji Live Casino Overview
    baji live 999 login
    Every casino in the world claims that its uniqueness and originality are the reasons for their existence, but what makes Baji Live casino so special is its unique history and modern technologies. Baji Live Casino is not only a place where you can bet your money on games; it’s also a blending of technology and the user interface that altogether gives an unprecedented gaming experience.

    History and Licensing
    Baji Live Casino is licensed by the Curacao Gaming Commission, one of the most problematic and legitimate online casino licences in the world. Why they chose Curacao would do Columbus be the most peaceful and the most economically sound. The most important thing is the game poker license of Curacao. It has these kinds of features:

    International Rights: Curacao’s gaming license is known for its honesty and transparency. It is accepted in many countries and is a legal way for operators to launch services into a wider spectrum of markets worldwide.
    Regulation with Control: Baji Live Casino should stay according to a variety of the different regulations which are the part of the license such as game fairness, user data protection, and the conduct of responsible gaming and security measures.
    Audits and Checks: An auditing team is responsible for conducting regular control procedures of the casino. They are bankrolled by eCOGRA, and their ultimate aim is to ensure casino compliance with convenient, fair play and user safety requirements.
    Transaction Security: Curacao is the place where special attention is paid to the protection of financial transactions, which is essential to the safety and prevention of fraud among the players as well.
    For additional access and to alleviate blockers, our website provides mirror URLs like baji live 365, baji live 999, and baji 888 live. By means of this service, users can make requests as though they are in an unrestricted area and carry out transactions. The whole system, also, gives a high level of trust and security to Baji Live Casino users, which of course makes it really attractive to everybody that wants to either learn or play at an online casino. The stick to such strict licensing standards is the evidence that Baji Live I not only manages, but it is also strengthening its image as a reliable and responsible gambling provider in the market.

  13. CurtisPeats表示:

    Новости высоких технологий http://barbie-games.ru/rossiiskii-bespilotnik-raspechatannyi-na-3d-printere и гаджетов.

  14. Roccofek表示:

    Актуальные новости техники http://barbie-games.ru/nachalo-elektronnoi-registracii-na-saite-kompleksnaia-bezopasnost-2015 и гаджетов.

  15. RobertVed表示:

    Новости высоких технологий: новинки
    http://barbie-games.ru/razrabotano-nebusheesia-steklo-v-osnove-kotorogo-lejit-pancir-molluskov компьютерной техники и мобильных телефонов

  16. Coreypooli表示:

    Свежие новости http://barbie-games.ru/poteplenie-k-osadkam технологий новинки компьютерной техники

  17. Rufusdot表示:

    Новости высоких технологий http://barbie-games.ru/chevron-pereneset-shtab-kvartiru-iz-kalifornii-v-tehas новинки компьютерной техники и мобильных телефонов

  18. This website is usually a walk-through you discover the details it suited you about this and didn’t know who need to. Glimpse here, and you’ll undoubtedly discover it.

  19. over the internet,Their own girlfriend to be able replacing shirts, clothing fashion, gear, talked about the sourcing cost of developing overpriced; a person wii fact yet it’s besides a lady’s perfect customer’s segment.

  20. Erb’s Palsy Lawyer Tools To Facilitate Your Life Everyday erb’s Palsy Law firms

  21. We still cannot quite think I’m able to often be some checking important points positioned on your webblog. Our neighbors and i are sincerely thankful with your generosity as well as giving me possibility pursue our chosen profession path. I appreciate you information I became with the web-site.

  22. Why All The Fuss Over Truck Accidents? truck accident attorney

  23. I’m curious to find out what blog system you’re utilizing? I’m experiencing some small security problems with my latest site and I would like to find something more safeguarded. Do you have any solutions?

  24. Yyokao表示:

    oral lactulose – purchase betahistine how to get betahistine without a prescription

  25. Find Out More About Stomach Anxiety Symptoms While Working
    From Home anxiety symptoms treatment

  26. My personal sis recommended me personally about your own internet website and exactly how excellent it really is. She’s correct, I’m really impressed with the writing and clever design. It appears in my experience you are merely itching the surface when it comes to what you might achieve, nevertheless you’re on a good begin!

  27. Took me time to learn all the feedback, but I actually loved the write-up. It proved to be Very beneficial to me and I’m positive to all the commenters here! It really is always superior when you can not solely be informed, but additionally entertained! I am positive you had enjoyable penning this post.

  28. Mazrrim表示:

    Здравствуйте!
    Где и как купить диплом о высшем образовании без лишних рисков
    rushkas-diplomyxx.ru/attestat-za-11-klass

  29. Five Things You Don’t Know About Semi Truck Case semi truck accident law firms

  30. Lazrpnv表示:

    Здравствуйте!
    Купить диплом любого ВУЗа.
    mans-diplomy.ru/diplom-tehnikuma

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。