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,217,442 Responses

  1. Darrelherse表示:

    en iyi slot siteler: en iyi slot siteleri 2024 – guvenilir slot siteleri 2024

  2. Darrelherse表示:

    en cok kazandiran slot siteleri: canl? slot siteleri – slot siteleri

  3. Lazrico表示:

    Здравствуйте!
    Мы можем предложить дипломы любой профессии по приятным тарифам.
    u-cars.ru/modules.php?name=Your_Account&op=userinfo&username=ojevu

  4. Darrelherse表示:

    casino slot siteleri: en iyi slot siteleri 2024 – guvenilir slot siteleri

  5. KevinSounc表示:

    http://slotsiteleri.bid/# guvenilir slot siteleri

  6. Medicament information for patients. What side effects?
    can i get oxcarbazepine price
    Some what you want to know about meds. Get now.

  7. you are actually a just right webmaster. The website loading pace is
    amazing. It sort of feels that you’re doing any unique trick.
    In addition, The contents are masterpiece. you’ve done a magnificent activity in this matter!

  8. Heү! I know this is somewhat off topic but I
    was wondering if үoᥙ knew where I could find a captcha
    plugin foг mmy comment form? I’m using the sasme
    blog platform as yiurs and I’m having difficulty finding one?
    Thanks a lot!

    Heere is my web blog :: best inmate text service

  9. As the health and wellness industry continues to grow, many natural product lines have emerged.
    Among them, Golden Farms CBD has garnered significant
    attention.

  10. java burn表示:

    Useful info. Lucky me I found your site accidentally, and I am surprised why this coincidence did not came about earlier!
    I bookmarked it.

  11. What’s up, just wanted to tell you, I loved this blog post.
    It was practical. Keep on posting!

    Also visit my webpage :: testoprime reviews

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

  13. Augustina表示:

    An impressive share! I have just forwarded this onto a coworker who had been doing a little
    research on this. And he actually bought me breakfast simply because
    I stumbled upon it for him… lol. So let me reword this….
    Thank YOU for the meal!! But yeah, thanx for spending time to talk
    about this issue here on your site.

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

  15. Hedin Bil表示:

    Hi there! Do you use Twitter? I’d like to follow you if
    that would be ok. I’m absolutely enjoying your blog and look forward
    to new updates.

  16. KevinSounc表示:

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

  17. KevinSounc表示:

    http://sweetbonanza.network/# sweet bonanza slot demo

  18. Why No One Cares About Citroen C3 Key Replacement citroen Key Programming

  19. batangtoto表示:

    you’re in point of fact a just right webmaster. The web site loading pace is incredible.
    It seems that you are doing any distinctive trick. In addition, The contents are masterpiece.
    you’ve performed a magnificent job on this topic!

  20. foremost of the definitions of amounts is just
    that that as a rule is a medium of exchange, a measure or a
    means of preserving value, https://slothana-coin.com/ and the unit of account.

  21. Howdy! I could have sworn I’ve visited this blog before but after going through some of the posts I realized it’s new to me.
    Nonetheless, I’m definitely delighted I discovered it and I’ll be
    book-marking it and checking back regularly!

  22. Darrelherse表示:

    slot siteleri guvenilir: en guvenilir slot siteleri – yeni slot siteleri

  23. KevinSounc表示:

    https://slotsiteleri.bid/# bonus veren slot siteleri

  24. In the ever-evolving field of diet and nutrition, the Keto Bod Keto Diet stands out
    as a revolutionary approach to weight loss and overall
    health.

  25. I’ve been exploring for a little bit for any high quality articles
    or blog posts in this sort of house . Exploring in Yahoo I
    finally stumbled upon this site. Studying this information So i am happy
    to convey that I have an incredibly just right uncanny feeling I came upon exactly what I
    needed. I such a lot without a doubt will make certain to don?t disregard this website and provides it a glance regularly.

  26. dancelover.tv表示:

    7 Simple Tips To Totally Rolling With Your 3 Wheel Rollator With Seat Uk storage 3 wheel rollator – dancelover.tv,

  27. Your way of explaining all in this paragraph is actually pleasant, every one be
    able to without difficulty understand it, Thanks a lot.

  28. KevinSounc表示:

    http://sweetbonanza.network/# sweet bonanza 90 tl

發佈留言

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