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,229,175 Responses

  1. KevinSounc表示:

    http://sweetbonanza.network/# pragmatic play sweet bonanza

  2. shkoh表示:

    May I simply say what a comfort to find someone that
    actually understands what they are discussing on the internet.
    You certainly realize how to bring a problem to light and make it important.
    More people should look at this and understand this side of your story.

    I was surprised that you are not more popular since you
    definitely possess the gift.

  3. I quite like looking through a post that can make men and women think.
    Also, thanks for allowing for me to comment!

  4. 1表示:

    I love wyat you ɡuys are uѕսаⅼlү upp too. Such clever work аnd coverage!

    Keeeρ up the amazing works guys I’ve addеd you guys ttߋ our blogroll.

    Feel free to visit my sife – 1

  5. Chad表示:

    Wow that was odd. I just wrote an very long comment but after I clicked submit
    my comment didn’t appear. Grrrr… well I’m not writing all that over again. Anyway,
    just wanted to say fantastic blog!

  6. Darrelherse表示:

    slot siteleri: slot oyunlar? siteleri – slot kumar siteleri

  7. Remarkable! Its in fact remarkable post, I have got much clear idea concerning from this paragraph.

  8. Darrelherse表示:

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

  9. How To Tell If You’re Prepared For Ford Focus Key Replacement ford mondeo key replacement

  10. Great beat ! I wish to apprentice even as you
    amend your web site, how could i subscribe for a weblog site?
    The account aided me a appropriate deal. I had been tiny bit familiar of this your broadcast provided brilliant transparent idea

  11. Buzzwords De-Buzzed: 10 Other Ways To Deliver Volkswagen Key Programming volkswagen key programming near me

  12. KevinSounc表示:

    http://slotsiteleri.bid/# slot oyunlar? siteleri

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

  14. Тhere’s ԁefinatеly а great deal to find out abhout this topic.
    I reaⅼly like all ߋߋf tthe points you’ve
    maⅾе.

    My sitе 1 – https://500px.com/p/jokumsenlmxlysgaard

  15. Darrelherse表示:

    slot siteleri bonus veren: oyun siteleri slot – slot oyunlar? siteleri

  16. I must thank you for the efforts you’ve put in writing this site.
    I’m hoping to view the same high-grade blog
    posts by you in the future as well. In truth, your creative writing abilities has encouraged me to get my own, personal website
    now 😉

  17. KevinSounc表示:

    https://sweetbonanza.network/# sweet bonanza yasal site

  18. blockchain表示:

    Good information. Lucky me I ran across your blog by chance (stumbleupon).
    I’ve book marked it for later!

  19. This post is priceless. How can I find out more?

  20. Если вы искали где отремонтировать сломаную технику, обратите внимание – ремонт бытовой техники

  21. Darrelherse表示:

    slot casino siteleri: slot siteleri bonus veren – slot oyunlar? siteleri

  22. RTP ONLINE表示:

    I need to to thank you for this good read!!
    I certainly loved every little bit of it. I have got you bookmarked to look at new
    stuff you post…

  23. Darrelherse表示:

    oyun siteleri slot: slot kumar siteleri – deneme bonusu veren slot siteleri

  24. “Секретна кнопка” – найкраща та гарантована роками, коаксиальный от hammer-center.com.ua протиугінна система.

  25. KevinSounc表示:

    http://slotsiteleri.bid/# canl? slot siteleri

  26. ev taşıma表示:

    Ev Taşıma | Profesyonel bir nakliyat firmasının taşınma sürecindeki rolünü bu kadar net bir şekilde açıklamanız çok faydalı olmuş. Kozcuoğlu Ev Taşıma olarak, müşterilerimize en iyi hizmeti sunmayı amaçlıyoruz.

  27. Good day! Do you use Twitter? I’d like to follow you if that would be ok.
    I’m undoubtedly enjoying your blog and look forward to new updates.

發佈留言

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