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,231,176 Responses

  1. HassanbuifS表示:

    https://ultrabet-tr.online/# ultrabet tr online
    deneme bonusu veren siteler yerliarama.org

  2. LarryCoell表示:

    deneme bonusu veren siteler yerliarama.org deneme bonusu veren siteler denemebonusu2026.com deneme bonusu veren siteler denemebonusu2026.com

  3. LarryCoell表示:

    deneme bonusu veren yeni siteler denemebonusuverensiteler.top deneme bonusu veren siteler yeni

  4. HassanbuifS表示:

    https://ultrabet-tr.online/# ultrabet giris
    deneme bonusu veren siteler yerliarama.org

  5. Тут можно преобрести сейфы от пожара сейф несгораемый

  6. Sazruxd表示:

    Как быстро получить диплом магистра? Легальные способы
    nwkqnvz5.ixbb.ru/viewtopic.php?id=312#p312

  7. Drug information. Short-Term Effects.
    get cheap celebrex without dr prescription
    All trends of pills. Read information now.

  8. CarrollUnton表示:

    deneme bonusu veren siteler yerliarama.org http://slot-tr.online/# az parayla cok kazandiran slot oyunlar?

  9. Diplomi_yhMl表示:

    купить диплом колледжа в спб купить диплом колледжа в спб .

  10. Diplomi_arkn表示:

    диплом купить курс 1russa-diploms.ru .

  11. Derekfar表示:

    ultrabet giris: ultrabet – ultrabet

  12. Diplomi_lbkn表示:

    купить срочно диплом купить срочно диплом .

  13. 1win aviator表示:

    Thanks for another fantastic article. Where else may
    anybody get that kind of info in such an ideal method of writing?
    I have a presentation subsequent week, and I’m at the look for
    such info.

  14. nexted.com表示:

    Party Scene 하이오피, nexted.com,

  15. This Is The Porsche Spare Key Case Study You’ll Never Forget porsche Insurance

  16. I have been surfing online more than 3 hous today, yеt
    I never found any interesting article lіkе yours. It’s pretty worth enoᥙgh for me.

    Personally, if all site owners aand bloggers made good ϲontent as you did, the web ᴡill be a lot more ᥙseful than ever before.

    Also visit my page: best inmate text service

  17. HassanbuifS表示:

    https://casinositeleri.win/# Casino Siteleri
    denemebonusuverensiteler.top

  18. I’ve been browsing on-line more than three hours today, but I by no means discovered any fascinating article
    like yours. It is pretty price enough for me.

    Personally, if all web owners and bloggers made excellent content material as you did, the internet
    will probably be a lot more useful than ever before.

  19. ClydePab表示:

    ultrabet bonus: ultrabet guncel – ultrabet bonus

  20. Guide To Locksmiths For Cars Near Me: The Intermediate Guide Towards Locksmiths For Cars Near Me Locksmiths For Cars Near Me

  21. HassanbuifS表示:

    https://ultrabet-tr.online/# ultrabet giris
    deneme bonusu veren siteler yeni

  22. Тут можно преобрести купить огнеупорный сейф огнеупорный сейф купить

  23. Why Incorporating A Word Or Phrase Into Your Life
    Will Make All The A Difference best coffee pod machine

  24. JohnnyTex表示:

    Веб агентство в Москве выполняет разработку сайтов на платформе Битрикс под ключ. Дополнительные услуги – продвижение в поисковых системах Яндекс и Гугл, техническая поддержка, обслуживание, аудит, тестирование, наполнение контентом, контекстная реклама и маркетинг разработка и поддержка сайтов на битрикс

  25. Derekfar表示:

    deneme bonusu veren siteler yeni: deneme bonusu veren yeni siteler – deneme bonusu veren siteler denemebonusu2026.com

  26. CarrollUnton表示:

    deneme bonusu veren siteler https://ultrabet-tr.online/# ultrabet guncel

  27. What’s The Job Market For Accident & Injury Lawyers Professionals?
    accident & Injury lawyers (wheeler-wiggins.mdwrite.net)

發佈留言

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