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); //排序後:法国话,京片子,英语,中国,中文
Тут делают продвижение продвижение в поисковых системах медицинского сайта seo. медицинских. сайтов
What this high school senior wants adults to know about classroom phone bans
онлайн юристы бесплатно
как получить консультацию по ипотеке в сбербанке
онлайн юридические услуги
сбер услуги для мастеров
сбер право отзывы
медиатор в бизнесе
сити арбитр юридическая компания официальный сайт
юридический сервис
сбер кредит наличными
сбербанк консультация по ипотеке
When my friends and I walked into homeroom on the first day of school this year, my teacher told all of us to put our phones in a black plastic box on an old desk by the classroom door.
Handing over our phones during class is an official school policy, and my teachers always make this announcement at the beginning of the school year. But teachers would usually forget about the box by third period on the first day, never to be mentioned again by the second day of school. This year, however, the policy stuck that entire first day — and every day since.
I asked my Latin teacher why the school was suddenly getting so strict on phones. It turns out that over the summer most of the teachers had read social psychologist Jonathan Haidt’s book “The Anxious Generation: How the Great Rewiring of Childhood Is Causing an Epidemic of Mental Illness.”
Haidt, the Thomas Cooley Professor of Ehtical Leadership at New York University Stern School of Business, argues that a phone-based childhood leads to mentally unhealthy kids who are unprepared for life and, in my Latin teacher’s words, it “really freaked us out.” Teachers were serious about taking our phones now.
It’s not just causing trouble at my school. Some 72% of public high school teachers in the United States say that cell phone distraction among their students is a major problem, according to a study published by the Pew Research Center in April. In high schools that already have cell phone policies, 60% of teachers say that the policies are very or somewhat difficult to enforce, the same study reported.
Several states have passed laws attempting to restrict cell phone use in schools, and California Gov. Gavin Newsom recently signed legislation requiring school districts to regulate cell phone use. At least seven of the 20 largest school districts in the nation have either banned phones during the school day or plan to do so.
The WNBA is having a real moment – Caitlin Clark and the league’s historic season by the numbers
юрист по семейным спорам
право домклик ру
семейный юрист москва
адвокат по семейным делам консультация
юридическое сопровождение сделки с недвижимостью стоимость
помощь при мошенничестве
правовые платформы
адвокат по семейным делам москва
юристы мошенники как вернуть деньги
услуги юриста по семейным делам
When many of us hear the “Fall Classic,” we automatically think of baseball’s World Series. I’m not sure that will be the case for future generations.
Yes, I’m being somewhat provocative with that line, but the WNBA Finals have arrived on the heels of what can only be described as a historic season for the league. Across a metric of statistics, it’s clear that America’s interest in the WNBA is at the highest point this century in large part because of Indiana Fever star Caitlin Clark.
Let’s start simple: Google searches. They’ve been higher this WNBA season, starting with the draft in April, than at any point since we’ve had data (2004). Searches for the WNBA are up over 300% compared to last season, up over 850% compared to five seasons ago, and have risen nearly 1,400% from a decade ago.
That is, the WNBA has been rising, and this year it really took off.
This interest has translated into revenue for the league. Attendance is up a staggering 48% from 2023. There wasn’t a single team with an average regular season home attendance of five figures (10,000+) in 2023. This season, there were six.
Leading the charge was Clark’s Fever. A little more than 4,000 people attended their average game in 2023, which ranked them second to last. This season, more than 17,000 did, a 319% rise that put them far and away ahead of any other WNBA team and ahead of five NBA teams, including the hometown Indiana Pacers.
We see the same pattern in merchandise. Sales are up 600% from last year. This includes the boost from rookie sensations Clark, who had the best-selling jersey, and Angel Reese of the Chicago Sky, who had the second-best-selling jersey.
I couldn’t refrain from commenting. Perfectly written.
The No. One Question That Everyone Working In Sports Toto Latest Results Must
Know How To Answer 첫가입 꽁머니
Are You In Search Of Inspiration? Check Out French Door Fridge
Freezer Uk French Door Fridge Plumbed Water (https://Telegra.Ph)
вывод из запоя на дому похмельная вывод из запоя на дому похмельная .
вывод из запоя анонимно https://www.vyvod-iz-zapoya-ekaterinburg14.ru .
Aw, this was an exceptionally nice post. Finding the time and actual effort to make a good article… but what can I say… I hesitate a whole lot and never seem to get nearly anything done.
bs2site.at
An interesting discussion is worth comment. I do think that you need to write more on this topic, it may not be a taboo subject but usually people do not speak about these topics. To the next! All the best!
ADHD Private Diagnosis UK: The Good, The Bad, And The Ugly private adhd assessment sheffield cost
просушка после потопа https://osushenie-pomeshcheniya-moskva.ru/
Five Qualities That People Search For In Every Ford Car Keys ford car Key replacement near Me
вывод из запоя дешево краснодар вывод из запоя дешево краснодар .
Guide To Daftar Akun Togel Resmi: The Intermediate Guide To Daftar Akun Togel Resmi Daftar Akun Togel Resmi (Togelsingapore85744.Blogofchange.Com)
вывод из запоя лечение краснодар вывод из запоя лечение краснодар .
o xxx com o xxx com .
I need to to thank you for this good read!! I definitely loved every little bit of it. I have got you book-marked to look at new stuff you post…
What You Must Forget About Improving Your Pull Out Sleeper Chair sleeper sectional Pull out
order metronidazole 400mg pills – metronidazole 400mg pill buy cenforce 100mg without prescription
I want to to thank you for this fantastic read!! I definitely loved every bit of it. I have you saved as a favorite to check out new things you post…
Профессиональный сервисный центр по ремонту электросамокатов в Москве.
Мы предлагаем: ремонт электросамокатов в москве
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
Howdy! This post couldn’t be written any better! Looking at this post reminds me of my previous roommate! He always kept talking about this. I am going to forward this information to him. Fairly certain he’s going to have a great read. Many thanks for sharing!
How To Make A Profitable Bentley Bentayga Key If You’re Not Business-Savvy bentley Continental gt keys
Профессиональный сервисный центр по ремонту моноблоков iMac в Москве.
Мы предлагаем: ремонт imac москва
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
Профессиональный сервисный центр по ремонту электросамокатов в Москве.
Мы предлагаем: ремонт руля электросамоката
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
Nice post. I learn something new and challenging on sites I stumbleupon on a daily basis. It will always be helpful to read through articles from other writers and use a little something from their web sites.
You’ll Never Guess This Buy Chest Freezer Uk’s Tricks buy chest freezer uk – fridgefreezers37368.life-wiki.com –
Тут делают продвижение создание медицинских сайтов под ключ создание сайта медицинского центра