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

11,157 Responses

  1. Methods for dilution antimicrobial susceptibility beadlets for beagles that grow aerobically—fifth edition.

  2. Ten Situations In Which You’ll Want To Learn About Lost Honda Key No Spare honda car key maker

  3. Hey your site looks a little bit weird in Opera on my office computer Mac .

  4. 11 Ways To Completely Redesign Your Car Locksmiths Mobile Locksmith For Cars
    (https://Telegra.Ph)

  5. I would really like you to become a guest poster on my blog.*”,~,

  6. Aw, this was an extremely good post. Taking a few minutes and actual effort to make a great article… but what can I say… I hesitate a whole lot and don’t manage to get anything done.

  7. Quiz: How Much Do You Know About Upvc Door? upvc door Fittings

  8. I delight in, lead to I found just what I used to be taking a look for. You have ended my four day long hunt! God Bless you man. Have a nice day. Bye

  9. I am curious to find out what blog system you are utilizing? I’m experiencing some minor security problems with my latest website and I would like to find something more safeguarded. Do you have any recommendations?

  10. купить мебельный поролон купить мебельный поролон .

  11. электрокарнизы кузьминки электрокарнизы кузьминки .

  12. DouglasHoapy表示:

    1xbet тото промокод
    1xBet provides specific bonuses for users in Singapore, including promo codes that offer free bets, deposit matches, or free spins. These bonuses are tailored to the preferences of Singaporean users.

  13. самые гениальные идеи бизнеса самые гениальные идеи бизнеса .

  14. интересные бизнес идеи интересные бизнес идеи .

  15. 15 Gifts For The Capsule Coffee Maker Lover In Your Life capsule coffee Machines

  16. Qbwvkq表示:

    ozobax for sale – order lioresal pill order generic feldene

  17. Профессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
    Мы предлагаем: ремонт крупногабаритной техники в казани
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  18. Профессиональный сервисный центр по ремонту стиральных машин с выездом на дом по Москве.
    Мы предлагаем: ремонт стиральных машин москва сервис
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  19. An fascinating discussion will be worth comment. I’m sure that you can write on this topic, it will not certainly be a taboo subject but normally individuals are there are not enough to talk on such topics. To another location. Cheers

  20. What’s The Job Market For What Is The Best Automatic Folding Mobility Scooter Professionals?
    best automatic folding Mobility scooter

  21. There couple of interesting points at some point in this article but I don’t determine if I see they all center to heart. You can find some validity but I most certainly will take hold opinion until I check into it further. Excellent write-up , thanks so we want more! Included with FeedBurner likewise

  22. 20 Irrefutable Myths About Espresso Machine
    Sale: Busted professional espresso machine for home

  23. Hi, extremely interesting article. My sister and I have been recently looking to find comprehensive info on this subject kind of stuff for a short time, but we didn’t until now. Do you think you can also make some youtube videos about this, I believe your website will be far more detailed in case you did. In any other case, oh well. I will be checking out on this website in the forseeable future. Email me to keep me up to date. granite countertops cleveland

  24. Sani-flo表示:

    This design is spectacular! You definitely know how to keep a reader entertained. Between your wit and your videos, I was almost moved to start my own blog (well, almost…HaHa!) Fantastic job. I really enjoyed what you had to say, and more than that, how you presented it. Too cool!

  25. In these days of austerity as well as relative anxiety about taking on debt, lots of people balk about the idea of having a credit card to make acquisition of merchandise or maybe pay for a vacation, preferring, instead only to rely on the particular tried plus trusted way of making settlement – raw cash. However, if you have the cash on hand to make the purchase in whole, then, paradoxically, that is the best time for you to use the credit card for several causes.

  26. I was curious if you ever considered changing the page layout of your blog? Its very well written; I love what youve got to say. But maybe you could a little more in the way of content so people could connect with it better. Youve got an awful lot of text for only having one or two pictures. Maybe you could space it out better?

發佈留言

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