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,122,877 Responses

  1. I used to be recommended this blog via my cousin. I am no longer sure whether or not this post is
    written by means of him as no one else recognise such distinct approximately my difficulty.
    You’re incredible! Thank you!

  2. Darrelherse表示:

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

  3. vegan shoes表示:

    Howdy would you mind letting me know which hosting company you’re working with?
    I’ve loaded your blog in 3 completely different browsers and I must say this
    blog loads a lot quicker then most. Can you suggest a good web hosting provider at a fair price?
    Many thanks, I appreciate it!

  4. You have made some good points there. I checked on the web for
    additional information about the issue and found most individuals will go along with your views on this web site.

  5. Rollator Foldable Tools To Help You Manage Your Everyday Lifethe Only Rollator Foldable
    Trick Every Individual Should Be Able To Rollator foldable

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

  7. This Is What Key Programming Near Me Will Look In 10 Years Time car key programer near me

  8. Pinterest表示:

    I dugg some of you post as I thought they were handy handy.

    Feel free to surf to my homepage … Pinterest

  9. Meds information for patients. What side effects?
    how can i get generic fluoxetine no prescription
    Some what you want to know about pills. Get information now.

  10. KevinSounc表示:

    https://denemebonusuverensiteler.win/# deneme bonusu veren siteler

  11. Darrelherse表示:

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

  12. What i do not understood is actually how you’re now not really
    much more smartly-preferred than you might be now. You are so intelligent.
    You understand thus considerably when it comes to this topic, made me for
    my part consider it from so many numerous angles.
    Its like women and men aren’t interested unless it’s one thing to
    accomplish with Lady gaga! Your own stuffs excellent.
    Always deal with it up!

  13. KevinSounc表示:

    https://sweetbonanza.network/# sweet bonanza hilesi

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

  15. Texas Holdem Secrets – Free – The Best Kept Secrets In Poker 프라그마틱 무료체험

  16. KevinSounc表示:

    https://slotsiteleri.bid/# slot kumar siteleri

  17. KevinSounc表示:

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

  18. 5 Killer Quora Answers On Situs Terpercaya situs terpercaya

  19. batangtoto表示:

    Nice post. I was checking continuously this blog
    and I’m impressed! Extremely helpful info particularly the last part 🙂 I care for such
    info much. I was seeking this certain information for a long time.
    Thank you and good luck.

  20. ULTRA K9 PRO表示:

    Very rapidly this web site will be famous amid all blogging
    viewers, due to it’s nice posts

    my site ULTRA K9 PRO

  21. Thanks , I have just been looking for information approximately this subject for a while and yours is the greatest I’ve came upon till now.
    However, what concerning the bottom line? Are you sure about the source?

  22. saç ekimi表示:

    saç ekimi

    Hello i am kavin, its my first occasion to commenting anyplace, when i read this post
    i thought i could also make comment due to this brilliant piece
    of writing.

  23. Excellent weblog here! Also your website quite a bit up fast!
    What host are you the usage of? Can I am getting your affiliate hyperlink for your host?
    I wish my web site loaded up as quickly as yours lol

  24. What i do not understood is if truth be told how you are now not actually much more neatly-favored than you might be now.
    You are so intelligent. You know thus significantly
    in relation to this subject, made me personally consider it from numerous numerous angles.
    Its like women and men don’t seem to be fascinated unless it is something to
    do with Girl gaga! Your own stuffs excellent. All the time take
    care of it up!

  25. Keto Pure ACV Keto is a dietary supplement that combines the benefits of the ketogenic diet with the power of apple cider
    vinegar (ACV) to help individuals lose weight and improve their overall health.

  26. Introduction: Golden Farms CBD has emerged
    as a distinguished name in the rapidly growing cannabidiol (CBD) market.

  27. This is my first time pay a visit at here and i am actually impressed to
    read everthing at one place.

發佈留言

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