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...

7,001 Responses

  1. Lazrjzl表示:

    Привет, друзья!
    Мы изготавливаем дипломы любой профессии по выгодным ценам.
    sumerki-twilight.ru/42590543-pochemu-pochemu-lyudi-

  2. professional dog trainings are expensive specially if you hire those dog trainers that can teach your dogs lots of tricks,,

  3. Nice one, there is actually some great facts on this post some of my subscribers may find this useful, will send them a link, many thanks.

  4. Eanrsmd表示:

    Здравствуйте!
    Мы изготавливаем дипломы психологов, юристов, экономистов и других профессий по приятным тарифам.
    golf.od.ua/forum/viewtopic.php?t=16601&highlight=

  5. WilliamDeeli表示:

    Здравствуйте!
    Мы изготавливаем дипломы.
    goodgame.ru/user/1627368

  6. электрокарниз дешево http://elektrokarniz2.ru/ .

  7. my God, i thought you were going to chip in with some decisive insght at the end there, not leave it with ‘we leave it to you to decide’.

  8. I do consider all the ideas you have introduced for your post. They are really convincing and will certainly work. Nonetheless, the posts are too quick for newbies. Could you please extend them a little from next time? Thank you for the post.

  9. I am typically to blogging and i also really appreciate your content. This article has truly peaks my interest. I will bookmark your blog and maintain checking achievable info.

  10. BTW, and I hope we do not drag this too long, but care to remind us just what kind of weapons were being used on Kurds by Saddams army? To the tune of hundreds of thousands of dead Talk about re-written history

  11. JeffreyBlemy表示:

    комплексное seo в москве продвижение сайта

  12. Hmm is anyone else having problems with the images on this blog loading? I’m trying to figure out if its a problem on my end or if it’s the blog. Any responses would be greatly appreciated.

  13. Jessewrify表示:

    The Significance of Vibrations Management Tools in Mechanical Systems
    Across industrial sites, machines and rotating devices serve as the core of operations. However, one of the highly prevalent challenges that may affect the functionality and lifespan is vibrations. Vibrations can result in a range of complications, ranging from lowered perfection as well as effectiveness to elevated deterioration, finally bringing about expensive downtime and maintenance. Such a situation is the point where vibration control apparatus becomes essential.

    Why Vibrations Mitigation is Important

    Resonance inside machines may lead to various detrimental effects:

    Lowered Production Productivity: Excessive oscillation might cause misalignment along with imbalance, reducing overall efficiency with such devices. Such might bring about slower manufacturing speed as well as elevated energy consumption.

    Greater Deterioration: Persistent vibration increases total deterioration of equipment components, bringing about additional repairs and an potential of unexpected unforeseen malfunctions. This does not just raises operational costs but also decreases the lifetime of the existing equipment.

    Protection Concerns: Uncontrolled vibration can introduce considerable dangers both to both the equipment and the machinery and the operators. In severe cases, serious conditions, such vibrations could lead to catastrophic equipment breakdown, endangering personnel as well as leading to extensive devastation to the premises.

    Accuracy and Quality Problems: In fields that rely on precise production, such as manufacturing as well as aerospace, resonance may bring about inaccuracies with the production process, causing faulty goods along with greater waste.

    Reasonably Priced Alternatives for Vibration Regulation

    Investing in oscillation control equipment is not just a necessity and a sound investment for all businesses that any industry involved with machinery. We offer modern vibration regulation equipment are designed to reduce vibrations from any machinery or rotational systems, ensuring seamless and efficient operations.

    What sets these tools apart is its its affordability. We know the value of cost-effectiveness inside today’s competitive market, which is why we provide high-quality oscillation control tools at prices that are reasonable.

    By choosing our offerings, you’re not only securing your mechanical systems along with increasing its performance but also putting investment in the long-term success in your organization.

    Final Thoughts

    Vibration management is an essential factor of maintaining the efficiency, safety, as well as lifespan of your machinery. With our affordable vibration control equipment, you can be certain your operations function efficiently, your products maintain top quality, and your employees stay safe. Don’t let vibrations undermine your machinery—invest in the right equipment today.

  14. I found your weblog website on google and examine a couple of of your early posts. Proceed to maintain up the very good operate. I simply extra up your RSS feed to my MSN Information Reader. Searching for forward to studying more from you afterward!…

  15. I respect your piece of work, appreciate it for all the interesting content .

  16. Awesome! I thank you your contribution to this matter. It has been insightful. my blog: how to make a girl like you

  17. I found your blog on yahoo and can bookmark it now. maintain the great work.

  18. Yes, really. I join told all above. We can communicate on this theme. Here or in PM.

  19. It’s nearly impossible to find knowledgeable folks on this topic, but the truth is could be seen as do you know what you are dealing with! Thanks

  20. A thoughtful insight and ideas I will use on my blog. You’ve obviously spent some time on this. Congratulations!

  21. электрокарниз от производителя elektrokarniz2.ru .

  22. I precisely had to thank you so much yet again. I do not know the things I might have implemented in the absence of the actual creative ideas shared by you on such a area of interest. It absolutely was an absolute frightful crisis in my opinion, but finding out your professional approach you solved it took me to leap with delight. I am happy for this guidance as well as wish you comprehend what an amazing job you were undertaking teaching many others through a blog. I know that you’ve never encountered all of us.

  23. gucci and prada also makes beautifully styled ladies shoes but are expensive-

  24. fashion jewelries will be one of the best stuffs that you can use to enhance your personal style’

  25. My spouse and I absolutely love your blog and find nearly all of your post’s to be precisely what I’m looking for. Would you offer guest writers to write content for you? I wouldn’t mind producing a post or elaborating on a few of the subjects you write about here. Again, awesome site!

發佈留言

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