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,230,334 Responses

  1. Willard表示:

    I like the valuable info you provide in your articles.
    I’ll bookmark your weblog and check again here regularly.
    I am quite certain I will learn lots of new stuff right here!
    Good luck for the next!

  2. This is the perfect webpage for anybody who really wants
    to understand this topic. You know so much its almost hard
    to argue with you (not that I actually would want to…HaHa).
    You definitely put a new spin on a subject
    that’s been discussed for decades. Great stuff, just wonderful!

  3. Good response in return of this issue with firm arguments and explaining the
    whole thing on the topic of that.

  4. Darrelherse表示:

    slot bahis siteleri: deneme bonusu veren slot siteleri – deneme bonusu veren slot siteleri

  5. Darrelherse表示:

    deneme bonusu veren siteler: en cok kazandiran slot siteleri – casino slot siteleri

  6. Quality articles or reviews is the key to invite the
    users to pay a visit the web page, that’s what this website is providing.

  7. ev taşıma表示:

    Evden Eve Nakliyat | Ev taşıma sürecinde planlamanın ne kadar önemli olduğunu bu yazınızda çok güzel anlatmışsınız. Kozcuoğlu Evden Eve Nakliyat olarak, her detayı titizlikle planlayarak müşterilerimize kusursuz bir taşınma deneyimi sunuyoruz.

  8. hello there and thank you for your info – I’ve certainly picked
    up something new from right here. I did however expertise some technical points
    using this website, as I experienced to reload
    the web site many times previous to I could get it to load properly.
    I had been wondering if your web hosting is OK?
    Not that I am complaining, but slow loading instances times will often affect your placement in google and could damage
    your high quality score if advertising and marketing with
    Adwords. Well I’m adding this RSS to my e-mail and could look out for much more of your respective intriguing
    content. Ensure that you update this again very soon.

  9. ev taşıma表示:

    Ev Taşıma | Taşınma sürecinde karşılaşılabilecek sorunlar ve çözümleri üzerine yazılmış bu makale çok bilgilendirici. Kozcuoğlu Ev Taşıma olarak, olası sorunları önceden önlemek için gerekli tüm tedbirleri alıyoruz.

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

  11. KevinSounc表示:

    http://denemebonusuverensiteler.win/# bonus veren siteler

  12. Darrelherse表示:

    en yeni slot siteleri: en cok kazandiran slot siteleri – slot oyunlar? siteleri

  13. Darrelherse表示:

    deneme bonusu veren slot siteleri: slot bahis siteleri – slot siteleri bonus veren

  14. Как избежать ошибок с дубликатами номеров, практические советы по предотвращению дубликатов номеров, простые шаги по избежанию дубликатов номеров. Показано, как эффективно бороться с дубликатами номеров, эффективные способы борьбы с дубликатами номеров. Полезные рекомендации по предотвращению дубликатов номеров, лучшие советы по избежанию дублирующихся номеров на документах. предотвратите дублирование номеров на бумагах с помощью этих советов, как предотвратить дублирующиеся номера на документах.
    дубликат номера автомобиля цена http://www.avto-znaki.com .

  15. Darrelherse表示:

    deneme bonusu veren siteler: slot bahis siteleri – slot siteleri guvenilir

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

  17. Darrelherse表示:

    en iyi slot siteler: en iyi slot siteler – canl? slot siteleri

  18. KevinSounc表示:

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

  19. Pretty portion of content. I just stumbled upon your blog
    and in accession capital to say that I acquire in fact loved account your weblog posts.
    Any way I will be subscribing to your feeds and even I achievement you access consistently rapidly.

  20. I read this paragraph fully concerning the comparison of newest and preceding technologies, it’s awesome
    article. https://Nwdp.CO.Uk/forum/profile/DamonTripp

  21. macauslot88表示:

    Hey! I could have sworn I’ve been to this website before but after checking through some of
    the post I realized it’s new to me. Nonetheless, I’m definitely glad I found it and I’ll be book-marking and
    checking back often!

  22. Slot Buah表示:

    If you are going for most excellent contents like I do, just go to see this web page every day for the reason that it gives
    quality contents, thanks

  23. KevinSounc表示:

    https://sweetbonanza.network/# sweet bonanza free spin demo

  24. Greetings , peer reader . I uncovered your profound analysis on the blog article
    highly keen .

    Your viewpoint on the content is considerably admirable .

    As you look to have a devoted investment in the matter
    , I wish to provide an invitation for you to investigate the realm of ‘918KISS’.

    This unique platform delivers a vast portfolio of compelling data that accordingly meet the needs of persons
    possessing eclectic pursuits .

    I gather you possibly locate the network at ‘918KISS’ as both
    enriching and academically absorbing .

    I implore you to ponder associating with us and contributing
    your invaluable understandings to the ongoing
    exchanges . Hopeful for hypothetically integrating you into our
    fold .

    Review my homepage :: online casino artificial intelligence

  25. husqvarna 365表示:

    I every time used to read paragraph in news papers but now as I am
    a user of net thus from now I am using net for content, thanks to web.

  26. Darrelherse表示:

    en iyi slot siteleri: slot siteleri bonus veren – en iyi slot siteleri 2024

  27. Hi, i think that i saw you visited my weblog thus i came to “return the favor”.I
    am attempting to find things to improve my website!I suppose
    its ok to use some of your ideas!!

  28. online survey表示:

    It is appropriate time to make a few plans for
    the longer term and it’s time to be happy. I have read this put up and if
    I may I wish to recommend you some interesting issues or suggestions.
    Maybe you can write subsequent articles regarding this article.
    I want to read even more issues about it!

  29. 14 Questions You Shouldn’t Be Refused To Ask Audi
    A4 Key Replacement Audi a3 Replacement key

發佈留言

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