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,466,580 Responses

  1. вывод из запоя на дому ростов недорого вывод из запоя на дому ростов недорого .

  2. врач на дом капельница от запоя врач на дом капельница от запоя .

  3. FrankEmine表示:

    deneme bonusu veren siteler yeni: denemebonusuverensiteler25 – deneme bonusu veren siteler

  4. certainly like your web site however you have to test
    the spelling on several of your posts. Several of them
    are rife with spelling issues and I in finding it very
    troublesome to inform the reality then again I’ll certainly come again again.

  5. A Peek Inside The Secrets Of Agency SEO Software Seo Agency West London

  6. выведение из запоя ростов на дону выведение из запоя ростов на дону .

  7. принудительный вывод из запоя ростов http://www.vyvod-iz-zapoya-rostov229.ru .

  8. вывод из запоя ростов на дону стационар vyvod-iz-zapoya-rostov228.ru .

  9. Irene Day表示:

    This was a fantastic read. Check out customized cleaning Medindie for more

  10. вывод из запоя в ростове на дону вывод из запоя в ростове на дону .

  11. Linnie Butler表示:

    The importance of proper drainage in commercial roofing cannot be overlooked! More info available at CR3 American Exteriors

  12. Lengkap melalui layanan pesan antar sistem jaringan kerjasama dengan Apotek. Online pharmacies, Online Pharmacies, Pharmacy Home Delivery, Selling. Hereby the ovaries to produce, our price kr3.99.Buy now. I stayed at the Apotek Hotel with my husband as part of our Iceland stay. Viagra Apotek Online, Cheap AND Secure, Creativitart. How Much Cost Glucophage online Generic Glucophage Where To Get. Pris Levitra Professional Viagra Soft billigt kopa natet utan recept, kan jag fa. Viagra Apotek Online, Eliminate Refractory Period. https://lakemedel.space/activelle/ Inkop Activelle Rabatt

  13. вывод из запоя ростов на дону на дому вывод из запоя ростов на дону на дому .

  14. капельница от запоя на дому круглосуточно [url=https://www.vyvod-iz-zapoya-rostov229.ru]капельница от запоя на дому круглосуточно[/url] .

  15. JasonUnsoG表示:

    https://casinositeleri25.com/# Deneme Bonusu Veren Siteler

  16. Della Frazier表示:

    This was very insightful. Check out Roof installation nearby for more

  17. 100 먹튀검증 먹튀사이트 목록 확인 커뮤니티 먹튀모음 토토사이트 메이저사이트 스포츠 미니게임 파워볼 꽁머니사이트 모든 사이트 먹튀검증을 시행하고 있으며, 가장 빠른 먹튀검증사이트입니다 먹튀모음은 먹튀에서 안전한
    공식 보증업체를 추천해드리며, 부당한 일을 당하지 않게 체계적인 시스템으로 운영하고 있습니다

  18. BradleyEdino表示:

    deneme bonusu veren siteler denemebonusuverensiteler25 yeni deneme bonusu veren siteler

  19. Wallacefex表示:

    Deneme Bonusu Veren Siteler: Casino Siteleri – casino bahis siteleri

  20. вывод из запоя на дому ростов недорого вывод из запоя на дому ростов недорого .

  21. Wallacefex表示:

    sweet bonanza kazanma saatleri: sweet bonanza oyna – sweet bonanza yorumlar

  22. вывод из запоя ростов [url=http://www.vyvod-iz-zapoya-rostov228.ru]вывод из запоя ростов[/url] .

  23. FrankEmine表示:

    sweet bonanza: sweet bonanza demo oyna – sweet bonanza giris

  24. Нey there! I’ve beеn folloԝing yߋᥙr blog fоr sߋme time
    now and finally got the courage to ɡo ahead and give you
    a shout out from Kingѡood Texas! Just wanted to mention keep up the ցookd work!

    Hеre is my site geometry dash unblocked

  25. The Reason The Biggest “Myths” About Buy Our C Driving License
    Gothenburg Could Be A Lie köp Körkort På webben

  26. Excellent beat ! I wish to apprentice while you amend your web site, how can i subscribe
    for a blog web site? The account helped me a acceptable deal.

    I had been tiny bit acquainted of this your broadcast offered bright clear idea

發佈留言

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