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,582 Responses

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

  2. thimbles game表示:

    Fantastic beat ! I wish to apprentice at the same time as you amend your web site, how can i subscribe for a blog web site?
    The account helped me a acceptable deal. I had been a little bit familiar of this your broadcast offered bright clear concept

  3. I’d lіke to fіnd out more? I’dwant to find out morе details.

    Here iѕ my webpage PokemonToto Alternatif

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

  5. Darrelherse表示:

    slot bahis siteleri: 2024 en iyi slot siteleri – slot oyunlar? siteleri

  6. Hey very cool blog!! Man .. Beautiful .. Wonderful ..
    I’ll bookmark your web site and take the feeds additionally?
    I’m happy to seek out numerous helpful info right here in the publish, we’d like develop extra techniques
    in this regard, thank you for sharing. . . . .
    .

  7. Good post. І learn sοmething new ɑnd challenging ᧐n blogs I stumbleupon оn ɑ
    daily basis. Ιt’s alᴡays ᥙseful to reɑd throᥙgh articles fromm ߋther authors and use a little ѕomething fгom ᧐ther sites.

    Feel free to visit mү web bpog :: PokemonToto Live Chat

  8. Darrelherse表示:

    bonus veren casino slot siteleri: deneme veren slot siteleri – deneme bonusu veren siteler

  9. 7 Little Changes That’ll Make The Difference With Your Land Rover Spare
    Key land rover discovery 2 key Replacement

  10. lawinplay表示:

    Lawinplay – You can Use GCash to play in anytime
    Free Spins 1000+ Free Demo Slot
    Openning Bonus 120% piso back
    Searching lawinplay888 on Google or Bing to get free coins

    https://lawinplay888.com

  11. Darrelherse表示:

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

  12. 101 game表示:

    Oh my goodness! Impressive article dude! Thank
    you, However I am having issues with your RSS.
    I don’t know the reason why I am unable to join it.
    Is there anybody else having similar RSS problems? Anyone that knows the answer can you kindly respond?
    Thanx!!

  13. Are You Getting The Most Out You Smart Car Key Replacement Near Me?
    smart fortwo key replacement

  14. I do not even know how I ended up here, but I thought this post was good.
    I do not know who you are but certainly you
    are going to a famous blogger if you aren’t already
    😉 Cheers!

  15. My partner and I stumbled over here different web page and thought I
    might check things out. I like what I see so now i am following you.
    Look forward to looking over your web page for a second time.

  16. Darrelherse表示:

    slot siteleri guvenilir: bonus veren casino slot siteleri – slot siteleri bonus veren

  17. milfpussy.fun表示:

    I visited several sites but the audio feature for audio songs existing at this site
    is in fact excellent.

  18. Darrelherse表示:

    en yeni slot siteleri: bonus veren casino slot siteleri – slot kumar siteleri

  19. Darrelherse表示:

    deneme veren slot siteleri: oyun siteleri slot – bonus veren slot siteleri

  20. KevinSounc表示:

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

  21. 9 . What Your Parents Taught You About Replacement Key For Renault Trafic
    Van replacement key For renault trafic van

  22. Лечебная физкультура и массаж. Помощь от болей в спине и теле. Коррекция осанки, плоскостопия.
    Преимущества сочетания ЛФК и массажа в лечении

  23. Unquestionable Evidence That You Need Smart Car Key Replacement Near Me smart Keys cars

  24. Anti Anxiety表示:

    I was able to find good info from your content.

  25. KevinSounc表示:

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

  26. learn more表示:

    Good post. I am going through many of these issues as well..

  27. Darrelherse表示:

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

  28. Evden Eve Nakliyat | Müşteri memnuniyetinin önemini vurgulayan bu makaleyi büyük bir ilgiyle okuduk. Kozcuoğlu Evden Eve Nakliyat olarak, her zaman müşteri memnuniyetini ön planda tutuyoruz.

  29. KevinSounc表示:

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

發佈留言

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