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,079 Responses

  1. Louiehaics表示:

    заказать хороший торт заказать хороший торт

  2. I enjoy looking through a post that can make people think. Also, many thanks for allowing me to comment.

  3. What Experts In The Field Want You To Know? cerebral palsy lawsuit

  4. Thanks for the suggestions you have provided here. Another thing I would like to state is that personal computer memory demands generally increase along with other innovations in the technology. For instance, if new generations of processor chips are brought to the market, there is usually a matching increase in the scale preferences of all laptop or computer memory in addition to hard drive space. This is because the software operated by simply these cpus will inevitably surge in power to use the new technology.

  5. when giving corporate gifts, you should also be creative to find the best gifts to give.

  6. my hard drive is getting full already because i always download free online movies on the internet“

  7. Trefpbh表示:

    Привет!
    Всё, что нужно знать о покупке аттестата о среднем образовании
    diplomman.ru/kupit-diplom-sssr
    Будем рады вам помочь!.

  8. leak finding表示:

    Real estate is very market specific and if you invest correctly, by city, geographical area within the city and even to individual neighborhoods and streets you can make quite a bit of money. Another great option is to encourage your customers to follow you on Twitter.

  9. nude chat表示:

    This is the right webpage for anybody who really wants to understand this topic. You realize a whole lot its almost tough to argue with you (not that I actually would want to…HaHa). You certainly put a fresh spin on a subject that’s been written about for years. Wonderful stuff, just excellent.

  10. Lazrvgo表示:

    Добрый день!
    Мы изготавливаем дипломы психологов, юристов, экономистов и любых других профессий по приятным ценам.
    rushkas-diplomy.ru/kupit-diplom-krasnodar

  11. bathtub leaks表示:

    I do consider all the ideas you’ve introduced on your post. They are very convincing and will definitely work. Nonetheless, the posts are very brief for starters. May just you please lengthen them a bit from subsequent time? Thanks for the post.

  12. Harry Potter is the best, i really like Daniel Radcliffe because he acts very well,,

  13. This is a topic which is near to my heart… Best wishes! Where are your contact details though?

  14. Diplomi_iuEa表示:

    Привет, друзья!
    Приобрести документ о получении высшего образования вы имеете возможность в нашей компании.
    rushkas-diploms.ru

  15. Richardexips表示:

    A chainsaw amnesty is protecting the rainforest in Borneo
    отзыв оставить

    Borneo was once covered in lush, dense rainforests, but they are rapidly disappearing. The Southeast Asian island, roughly three times the size of the UK, has lost half its forest cover since the 1930s, destroying precious habitat for wildlife such as the critically endangered orangutan, as well as valuable carbon stores.

    A non-profit called Health in Harmony (HIH) is asking farmers to hand in their chainsaws in return for money, and a chance to set up an alternative livelihood.

    Borneo is divided between Indonesia, Malaysia and Brunei, and it is estimated that up to 10% of its land is taken up by industrial palm oil and logging operations. But deforestation isn’t just about large-scale tree clearance; some of those behind the logging are small-scale farmers, cutting trees as a sideline to make ends meet.

    Buyback and healthcare
    HIH launched its chainsaw buyback scheme in 2017, under the group’s Indonesian name, Alam Sehat Lestari (ASRI). Farmers who illegally log and sell the wood to timber companies are given around $200 for their chainsaws, as well as up to $450 in financial support for them to set up an alternative, sustainable livelihood, such as opening a shop, organic farming and even beekeeping.

    The scheme also involves addressing the root causes of the problem. According to HIH, many of the farmers who turn to logging do so because they need the money for basics like healthcare.

    “They live far from the healthcare clinics, and they see logging as a place where they can get quick cash,” explained Mahardika “Dika” Putra, conservation program manager at HIH. “If they need this amount of money, they cut this amount of trees.

    “We asked what solutions they think they need to live in harmony with the forest and they said, ‘high quality, affordable healthcare, and training in organic farming.’”

  16. Lytghh表示:

    buy trileptal 600mg without prescription – order oxcarbazepine 600mg generic buy levothroid online cheap

  17. ngentot memek表示:

    This is a topic which is close to my heart… Best wishes! Where are your contact details though?

  18. Mazrlua表示:

    Здравствуйте!
    Официальная покупка школьного аттестата с упрощенным обучением в Москве
    rushkadiplomik.ru

  19. link bokep表示:

    You have made some good points there. I checked on the internet to find out more about the issue and found most individuals will go along with your views on this web site.

  20. What’s The Job Market For Espresso Machine With Grinder Professionals Like?
    Espresso Machine With Grinder

  21. heavy window curtains would be much needed this december to conserve more heat**

  22. Hello, I found your blog in a very new directory of blogs. I don’t learn how your site came up, need to have been a typo. Your blog looks good, have a nice day.

  23. Think You’re Ready To Start Double And Single Bunk?

    Take This Quiz single double bunk Bed

  24. There are certainly a number of particulars like that to take into consideration. That is a great level to convey up. I supply the ideas above as normal inspiration but clearly there are questions like the one you deliver up where an important thing will likely be working in honest good faith. I don?t know if finest practices have emerged around issues like that, however I am sure that your job is clearly identified as a fair game. Both boys and girls really feel the affect of only a second’s pleasure, for the rest of their lives. Miss Verlene

  25. Hi mate, .This was an excellent page for such a complicated topic to talk about. I look forward to reading many more excellent posts like this one. Thanks

  26. This site may be a walk-through like the knowledge you wanted concerning this and didn’t know who ought to. Glimpse here, and you’ll absolutely discover it.

  27. Where exactly can I get a hold of this page layout?

  28. You should take part in a contest for one of the greatest blogs online. I am going to recommend this site!

  29. 10 Quick Tips For Tree House Bunk Bed childrens treehouse bed

  30. Trefrgh表示:

    Здравствуйте!
    Узнайте, как безопасно купить диплом о высшем образовании
    mans-diplomy.ru/kupit-diplom-voronezh
    Рады оказать помощь!.

發佈留言

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