JS 依照元素出現數量排序

同樣是最近遇到的狀況,需要利用陣列內元素出現的數量進行排序,以下為範例程式:

var array = ["1", "2", "4", "5", "2", "4", "2", "3"];
var str = array.toString();
var filter = [];
var result = [];
document.write("原始陣列:" + array + "<br>");

var get = function (str, tar, arr, tmp) {
    if (str.indexOf(tar) >= 0) {
        tmp = str.slice(str.indexOf(tar) + 1);
        arr.push(tar);
        get(tmp, tar, arr, tmp);
    }
    return arr;
}

for (i in array) {
    var elm = [];
    var tmp;
    var fstr = filter.join();
    if (fstr.indexOf(array[i]) >= 0) {
        continue;
    } else {
        var tmp_arr = get(str, array[i], elm, tmp);
        result.push(tmp_arr.length + ':' + tmp_arr[0]);
        filter.push(array[i]);
    }
}

result.sort();
result.reverse();

//按照出現次數排序,不刪除重複元素
var finishArray = [];

for (index in result) {
    var show = result[index].split(':');
    for (i = 0; i < show[0]; i++) {
        finishArray.push(show[1]);
    }
}
document.write("按出現次數排序,不刪除重複元素:" + finishArray + "<br>");

//按照出現次數排序,刪除重複元素
var finishArray = [];
for (index in result) {
    var show = result[index].split(':');
    finishArray.push(show[1]);
}
document.write("按出現次數排序,刪除重複元素:" + finishArray + "<br>");

輸出結果:

原始陣列:1,2,4,5,2,4,2,3
按出現次數排序,不刪除重複元素:2,2,2,4,4,5,3,1
按出現次數排序,刪除重複元素:2,4,5,3,1

You may also like...

1,233,343 Responses

  1. silebet.com表示:

    Appreciating the time and effort you put into
    your site and in depth information you provide. It’s good to come across a blog every once in a while that isn’t the
    same unwanted rehashed material. Wonderful read! I’ve bookmarked your site and I’m adding your RSS feeds
    to my Google account.

  2. Appreciate the recommendation. Let me try it out.

  3. KevinSounc表示:

    http://slotsiteleri.bid/# en yeni slot siteleri

  4. KevinSounc表示:

    https://sweetbonanza.network/# sweet bonanza demo oyna

  5. The Reason Why You’re Not Succeeding At Hyundai I30 Replacement Key Hyundai key replacement cost uk

  6. Chrismew表示:

    לכן אין לשפוט אף אחד. אם אישה קונה דילדו גדול, או גבר הולך לבלות עם נערות ליווי – זכרו תמיד כי כולם רוצים ליהנות מסקס. ליווי חרמניות שרוצות לבלות עם גברים בתל אביב. אתה יכול למצוא כאן היצע גדול של נערות חרמניות העובדות בתל אביב, ותוכל להזמין כל sneak a peek at this web-site

  7. Undeniably consider that which you stated. Your favourite justification seemed to be on the web the simplest thing to take
    note of. I say to you, I certainly get irked even as folks consider worries that they plainly don’t understand about.
    You controlled to hit the nail upon the highest as neatly as outlined out the
    entire thing with no need side effect , people can take a
    signal. Will likely be back to get more. Thanks

  8. Ofelia表示:

    Hiya! Quick question that’s totally off topic. Do you know how
    to make your site mobile friendly? My web site looks weird when browsing from my apple iphone.
    I’m trying to find a theme or plugin that might be able to resolve
    this problem. If you have any suggestions,
    please share. With thanks!

  9. Asking questions are genuinely nice thing if you are not understanding anything fully,
    however this paragraph presents pleasant understanding even.

  10. Darrelherse表示:

    deneme bonusu veren siteler: slot oyunlar? siteleri – guvenilir slot siteleri 2024

  11. Hey there! This is kind of off topic but I need some help from an established blog.
    Is it difficult to set up your own blog? I’m not very techincal
    but I can figure things out pretty fast. I’m thinking about creating
    my own but I’m not sure where to begin. Do you have any ideas or suggestions?
    Thank you

  12. Чтобы подарок казино стал доступен для вывода
    и перешел на основной баланс, его необходимо отыграть.

  13. Lazrcav表示:

    Привет!
    Мы изготавливаем дипломы психологов, юристов, экономистов и прочих профессий по доступным ценам.
    u-cars.ru/modules.php?name=Your_Account&op=userinfo&username=ojevu

  14. Darrelherse表示:

    slot oyunlar? siteleri: slot siteleri 2024 – deneme bonusu veren slot siteleri

  15. KevinSounc表示:

    http://slotsiteleri.bid/# 2024 en iyi slot siteleri

  16. Medicine information sheet. What side effects?
    buying trileptal for sale
    Best trends of drugs. Get here.

  17. Thanks for finally writing about > JS 依照元素出現數量排序 – 馬老師 雲端研究室 < Loved it!

  18. sexcams.ai表示:

    I’ve seen many things in my life as a webcam model.

  19. What’s up, its good paragraph regarding media print, we all know media
    is a fantastic source of data.

  20. Darrelherse表示:

    en cok kazandiran slot siteleri: slot kumar siteleri – en iyi slot siteleri 2024

  21. KevinSounc表示:

    http://sweetbonanza.network/# sweet bonanza mostbet

  22. Sarrbet.com表示:

    My coder is trying to persuade me to move to .net from PHP.
    I have always disliked the idea because of the expenses.
    But he’s tryiong none the less. I’ve been using WordPress on several websites
    for about a year and am concerned about switching to another platform.
    I have heard very good things about blogengine.net. Is there a way I can transfer all my wordpress content into it?
    Any kind of help would be greatly appreciated!

  23. Hurrah! In the end I got a webpage from where I be able to
    genuinely take helpful information regarding my study and
    knowledge.

  24. ev taşıma表示:

    Evden Eve Nakliyat | Ev taşımanın püf noktalarına değindiğiniz için teşekkürler. Kozcuoğlu Evden Eve Nakliyat olarak, taşınma sürecinde müşterilerimizin yanındayız ve profesyonel destek sağlıyoruz.

  25. Hi there, i read your blog occasionally and i own a similar one and i was just curious
    if you get a lot of spam responses? If so how do you reduce it, any plugin or
    anything you can recommend? I get so much lately it’s driving me mad so any assistance is very much appreciated.

    Also visit my site … bulk bath bombs

發佈留言

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