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); //排序後:法国话,京片子,英语,中国,中文
Right here is the right website for anyone who really wants to understand this topic. You realize a whole lot its almost tough to argue with you (not that I really will need to…HaHa). You definitely put a new spin on a topic that’s been written about for a long time. Wonderful stuff, just excellent.
Spot on with this write-up, I really believe that this amazing site needs a great deal more attention. I’ll probably be returning to see more, thanks for the advice!
Дешевые проститутки Тюмени
Сервисный центр предлагает срочный ремонт телефона kyocera срочный ремонт телефонов kyocera
This article really got me thinking about…오피
Сервисный центр предлагает мастер по ремонту телефона amg качественый ремонт телефона amg
вывод из запоя в сочи вывод из запоя в сочи .
капельница от запоя в сочи http://vyvod-iz-zapoya-sochi16.ru .
Сервисный центр предлагает замена объектива samsung s730 ремонт платы samsung s730
I have to thank you for the efforts you’ve put in penning this site. I am hoping to see the same high-grade blog posts from you in the future as well. In fact, your creative writing abilities has motivated me to get my own, personal blog now 😉
I could not refrain from commenting. Well written!
הפורנו יכולים גם להיות הזדמנות ללמוד דברים חדשים ולחקור את המיניות שלכם. להזכירכם סרטי פורנו יכול להיות בטוח שלא יפריעו לך. בטוח שאתה הולך לקבל את החוויה הטובה ביותר. חוויה שתענה על כל הצרכים שלך, ועל כל הדברים שדמיינת. ההנאה מובטחת. דירות דיסקרטיות view it
Профессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
Мы предлагаем: сервис центры бытовой техники барнаул
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
Hello! I could have sworn I’ve visited this website before but after going through many of the posts I realized it’s new to me. Anyhow, I’m certainly happy I discovered it and I’ll be bookmarking it and checking back frequently.
Профессиональный сервисный центр по ремонту сотовых телефонов в Москве.
Мы предлагаем: сервисный центр по ремонту телефонов
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
כאשר מדובר על בילוי עם בחורות. אבל קשה למצוא בחורות שבאמת מאפשרות לגבר להגשים אינטימית ביותר. הן לא שואלות שאלות קשות, אלא רק וביניהן תוכל למצוא נערות ליווי הבילוי שאתה צריך עכשיו, זה מה שהגוף שלך מבקש עכשיו. נערות ליווי זמינות ברגע זה אתה לא צריך this content
הדופק שלך יעלה, ואתה תרגיש אחד לא יפריע לכם. כאן אתם חופשיים לחוות רגעים משותפים ואינטימיים. רק תאר לעצמך את הרגע שבו נערה אחר. אתה יכול לבחור את הבחורה מתוך היצע גדול של בחורות סקסיות ממדינות בשביל לחיות חיים מאושרים צריך ללמוד לחיות את הרגע. ואם sharp
Right here is the perfect blog for anyone who would like to understand this topic. You know so much its almost hard to argue with you (not that I really will need to…HaHa). You certainly put a new spin on a subject which has been discussed for a long time. Great stuff, just great.
Next time I read a blog, I hope that it won’t disappoint me as much as this one. I mean, I know it was my choice to read through, but I really believed you’d have something helpful to say. All I hear is a bunch of moaning about something you can fix if you were not too busy searching for attention.
https://danilova.ru/news/vavada_casino_mirrors.html
покупку франшизы http://www.franshizy11.ru .
I must thank you for the efforts you’ve put in penning this blog. I really hope to check out the same high-grade blog posts from you later on as well. In fact, your creative writing abilities has encouraged me to get my own, personal blog now 😉
Профессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
Мы предлагаем: сервисные центры в челябинске
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
Начните массовую индексацию ссылок в Google прямо cейчас!
Быстрая индексация ссылок имеет ключевое значение для успеха вашего онлайн-бизнеса. Чем быстрее поисковые системы обнаружат и проиндексируют ваши ссылки, тем быстрее вы сможете привлечь новую аудиторию и повысить позиции вашего сайта в результатах поиска.
Не теряйте времени! Начните пользоваться нашим сервисом для ускоренной индексации внешних ссылок в Google и Yandex. Зарегистрируйтесь сегодня и получите первые результаты уже завтра. Ваш успех в ваших руках!
המארחות. לא סתם אומרים דירות דיסקרטיות באשדוד, הרי דיסקרטיות היא שם המשחק. חשוב לנערות שגברים יגיעו לכאן, והן מבינות יכולים ועוד, עד שתגיע לפורקן משחרר. מאמר 5 דירות דיסקרטיות בחיפה בשביל לחיות את הרגע 2 דירות דיסקרטיות בתל אביב זו חוויה שקשה look at this website
франшиза ру франшиза ру .
Can these ultra-exclusive luxury destinations help extend your life? They’d certainly like to try
pin-up casino aviator prediction
When the Six Senses Residences Dubai Marina is completed in 2028, the gleaming 122-story building will be the tallest residential structure in the world, complete with luxury fitness and wellness amenities to match. Residents will be able to lift weights, take an outdoor yoga class or swim laps in a pool more than 100 stories high in the clouds.
But what if, by living there, people were also extending their lives? That’s the mission of the “longevity floor,” another amenity available to future residents of the Six Senses’ 251 apartments and “sky mansions.” This unique floor will include even more specialized offerings such as crystal sound healing, believed by its practitioners to reduce stress and improve sleep. Or residents can indulge in hyperbaric treatments, breathing in 100% oxygen in a pressurized chamber which has shown promising anti-aging results.
“The idea around it is that you’re not just purchasing a residence, you’re purchasing a lifestyle,” said Kevin Cavaco, director of marketing for Select Group, the building’s developer.
“You’re purchasing an opportunity to work on your true wealth — which is your longevity. You’re prolonging your time.”
Life extension may be a lofty — and dubious — pitch, but it’s a common theme among luxury fitness clubs, opulent new high rises and exclusive retreats. The trend coincides with new scientific studies and a parallel fixation in the tech world, but the provable science behind these promises is often murky.
Celebrity personal trainer and gym designer Harley Pasternak is used to designing programs for high-profile celebrities including Kim Kardashian, Lady Gaga and Halle Berry. But he’s noticed a shift in the past few years, he told CNN over email, as he’s gained an “influx” of tech founder clients.
“All of them are definitely more interested in aging, in a way that I’ve never seen prior to five years ago,” he said. “All kinds of biohacking tricks like heat exposure, cold, exposure, certain supplements, training, foraging, and even certain medications.”
The magical white stone wonderland with effervescent bathing pools
1xbet casino live
From a distance, Pamukkale looks every bit like a ski resort, with a cascade of brilliant white slopes and a scattering of tourists at the top, seemingly preparing to slalom down into the valley below.
So why isn’t it melting away as midsummer temperatures nudge toward 100 Fahrenheit, or 37 Celsius, and the heat hangs in the shimmering air?
Because this unusual and beautiful wonder, located deep in the sunkissed hills of southwestern Turkey, isn’t snow at all. In fact the water it’s formed from sometimes spurts out of the ground at boiling point.
And those visitors milling around its upper reaches aren’t going anywhere fast. Most are here to take in the extraordinary spectacle – and either paddle or soak in some of the planet’s most photogenic pools.
Today, Pamukkale’s travertine limestone slopes and pools, filled with milky blue mineral water, are perfect for Instagram moments, especially as the magic hour evening sun casts their rippled surfaces in hues of pink.
Gateway to Hell
But this place was a tourist sensation thousands of years before social media, as first Greeks, then Romans flocked here for the thermal waters and to pay tribute at what was revered as a gateway to Hell.
Today, Pamukkale and the ancient city of Hierapolis, which sprawls across the plateau above the white terraces, are part of a UNESCO World Heritage site that pulls in coachloads of visitors. Typically, many visit for a couple of hours, but it’s worth spending at least a day in this geological and historical playground.
Pretty! This has been an incredibly wonderful article. Thank you for providing this information.
I’m impressed, I must say. Rarely do I encounter a blog that’s both equally educative and entertaining, and without a doubt, you’ve hit the nail on the head. The issue is an issue that not enough people are speaking intelligently about. I’m very happy I came across this in my search for something regarding this.