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,449,396 Responses

  1. Iyannaobesk表示:

    покерная школа покерстарс
    уроки в школе покера покерстарс

  2. Very rapidly this web site will be famous among all blogging and
    site-building users, due to it’s pleasant articles

  3. Brandonnot表示:

    Mexican Easy Pharm: mexican rx online – Mexican Easy Pharm

  4. Carrolleruck表示:

    https://mexicaneasypharm.shop/# Mexican Easy Pharm
    canada pharmacy world

  5. I found this very interesting. For more, visit استخدام نیروی نمایشگاهی

  6. CurtisBam表示:

    Mexican Easy Pharm: Mexican Easy Pharm – Mexican Easy Pharm

  7. вывод из запоя в стационаре нижний новгород вывод из запоя в стационаре нижний новгород .

  8. UG8表示:

    This article is really a good one it assists new internet viewers,
    who are wishing for blogging.

  9. Trostaxum App表示:

    I always emailed this webpage post page to all my
    contacts, for the reason that if like to read it then my contacts will too.

  10. вывод из запоя в стационаре воронежа http://vyvod-iz-zapoya-v-stacionare-voronezh24.ru .

  11. Brandonnot表示:

    Best online Indian pharmacy: Indian Cert Pharm – Indian Cert Pharm

  12. JacobLoody表示:

    http://nedra2021.ru/ — создаём кухни, отражающие ваш стиль.

  13. CurtisBam表示:

    Mexican Easy Pharm: mexican rx online – Mexican Easy Pharm

  14. Os brasileiros participantes desfrutam de um preocupação!
    As seguinte impressões do sítio Web actividades indústria são as do jogos de azar actividades.
    Estes jogos apresentam método, ótimo acaso, multiplicadores, e um
    monte de sentimento. Eles foram projetados por designers.
    À medida que o jogo progride, os atletas são obrigados
    a apostar no compostos pré-jogo crenças à medida que o multiplicador cresce.
    Porque um ferimento está prestes a ocorrer, o objetivo é dinheiro
    quando as coisas estão a correr corretamente. https://groups.google.com/g/sheasjkdcdjksaksda/c/uNi5f0rKr7k

  15. I appreciate reading through your websites. Cheers!

    https://czas.tygodnik.pl

  16. CurtisBam表示:

    canadian pharmacy scam: Canadian Md Pharm – legit canadian pharmacy online

  17. CurtisBam表示:

    canadian pharmacies: CanadianMdPharm – is canadian pharmacy legit

  18. Mary McDonald表示:

    I appreciate this reminder that even small things matter when it comes upkeep—will definitely reach outtoWilsonWindowssoon!!!## anykeyword pressure washing company rates

  19. quietum plus表示:

    Hurrah, that’s what I was searching for, what a stuff!
    existing here at this weblog, thanks admin of this web page.

  20. generic co-amoxiclav without dr prescription where buy cheap co-amoxiclav without insurance where buy generic co-amoxiclav without insurance
    order generic co-amoxiclav pills can i buy generic co-amoxiclav without a prescription where buy generic co-amoxiclav pill
    how can i get generic co-amoxiclav prices
    can i get co-amoxiclav can you buy generic co-amoxiclav tablets how to buy cheap co-amoxiclav price
    where buy generic co-amoxiclav online order cheap co-amoxiclav without prescription can you get generic co-amoxiclav without rx

  21. Lestersarly表示:

    купить алкоголь с доставкой доставка алкоголя ночью

  22. Ora Dixon表示:

    Very informative article. For similar content, visit رنگ ضد حریق

  23. CurtisBam表示:

    pharmacies in mexico that ship to usa: Mexican Easy Pharm – Mexican Easy Pharm

  24. You’ll Be Unable To Guess Who Replaces Guttering’s Tricks who replaces guttering (mozillabd.science)

  25. CurtisBam表示:

    reliable canadian pharmacy: canadian pharmacy checker – canadian online pharmacy reviews

  26. Rickyalies表示:

    Удобный интерфейс позволяет быстро находить нужные данные, а дополнительные функции, такие как сравнение курсов в разных банках и отображение исторических графиков, делают использование сервиса максимально комфортным курс валюты на сегодня в банках

  27. Keep up the outstanding work !! Lovin’ it!
    https://wrzesnia.info.pl/pl/

發佈留言

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