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,599,299 Responses

  1. скупка золота 585 пробы цена b-gold.ru http://www.of-md.com/jwe-qs/ .

  2. LanceFen表示:

    Clom Fast Pharm: can i purchase cheap clomid without insurance – how to get cheap clomid

  3. скупка золота дорого в москве b-gold.ru скупка золота дорого в москве b-gold.ru .

  4. Thanks to my father who told me regarding this website,
    this web site is truly amazing.

  5. WebSite - so表示:

    The Appeal of Online Gambling
    More and more players are choosing online gambling for its unmatched convenience and variety. Perhaps the most appealing aspect is how easy it is to access games. While land-based casinos have restrictions, online platforms operate 24/7, letting players enjoy their favorite games at any time.

    The vast selection of games also contributes to the widespread appeal. Physical casinos may offer a few hundred games at best, but digital platforms feature thousands. Whether you love old-school slots or cinematic video games, there’s something for everyone. For exclusive deals and insights into the best casinos, check out our social media page! – https://www.kingbel.com/1win-casino-online-y-casa-de-apuestas-para-diversion-y-emociones/

    Bonuses, Rewards, and Promotions

    The abundance of promotions is one of the key benefits of playing at online casinos. Signing up usually comes with exciting perks like extra cash or free slot spins. The more you play, the more rewards you unlock, from cashback to personalized bonuses. While many casino games are based purely on luck, some require skill and strategy. For those who enjoy strategic play, poker offers opportunities to refine skills and increase winning chances. If you prefer a fast-paced, unpredictable experience, slots and roulette provide thrilling, luck-based gameplay.Finding a Secure and Fair Casino

    While online casinos offer fun and potential winnings, responsible gambling is crucial. Smart bankroll management and self-control help players maintain a healthy approach to gambling. Licensed casinos provide responsible gambling measures, such as cooling-off periods and withdrawal restrictions, to help players stay in control. Are you an online casino enthusiast? What’s your go-to game? Share your thoughts and experiences in the comments below!

  6. Danieldrymn表示:

    ZithPharmOnline: where can i purchase zithromax online – ZithPharmOnline

  7. скупка золота в москве за грамм 585 b-gold.ru скупка золота в москве за грамм 585 b-gold.ru .

  8. самая выгодная скупка золота в москве b-gold.ru http://www.www.of-md.com/jwe-qs/ .

  9. Danieldrymn表示:

    Clom Fast Pharm: Clom Fast Pharm – Clom Fast Pharm

  10. Vios4d表示:

    Panduan Praktis: Maksimalkan Bonus dan Free Spins di Action Boost: Gorilla Gems Vios4D

  11. Michaelscoob表示:

    where buy generic clomid: where can i buy cheap clomid pill – Clom Fast Pharm

  12. mostbet_exsr表示:

    поддержка мостбет http://www.mostbet6029.ru .

  13. Richardaudit表示:

    https://amonlinepharm.shop/# amoxicillin 500mg without prescription

  14. Cazrsne表示:

    Здравствуйте!
    Без присутствия диплома достаточно сложно было продвинуться по карьере. На текущий момент этот документ не дает никаких гарантий, что получится получить привлекательную работу. Более важное значение имеют навыки специалиста, а также его постоянный опыт. По этой причине решение о заказе диплома стоит считать целесообразным. Купить диплом любого ВУЗа finansi.5nx.ru/viewtopic.php?f=2&t=1286

  15. LanceFen表示:

    AmOnlinePharm: AmOnlinePharm – amoxicillin generic

  16. LanceFen表示:

    Clom Fast Pharm: how to get generic clomid no prescription – Clom Fast Pharm

  17. Cazrxvg表示:

    Добрый день!
    Мы изготавливаем дипломы любых профессий по приятным тарифам. Цена зависит от определенной специальности, года выпуска и образовательного учреждения: rdiploman.com/

  18. Richardaudit表示:

    https://clomfastpharm.com/# where to buy generic clomid

  19. DarylFerma表示:

    На сайте films2025.my вы можете смотреть новинки кино 2025 года абсолютно бесплатно. Удобная навигация по жанрам — от комедий и боевиков до фантастики и семейных фильмов — позволяет быстро найти интересующую вас картину. Все фильмы доступны в высоком качестве HD и без регистрации. Отличный выбор для вечернего просмотра смотреть мелодрамы бесплатно

  20. Michaelscoob表示:

    generic amoxil 500 mg: buy cheap amoxicillin online – amoxicillin 500mg price canada

  21. If you wish for to grow your familiarity only keep visiting this site and
    be updated with the newest news posted here.

  22. Richardaudit表示:

    https://amonlinepharm.com/# AmOnlinePharm

  23. Michaelscoob表示:

    ZithPharmOnline: generic zithromax india – zithromax coupon

  24. Diplomi_tjEa表示:

    Купить диплом любого университета!
    Мы готовы предложить документы университетов, которые расположены на территории всей Российской Федерации.
    diplomt-nsk.ru/kupit-diplom-s-reestrom-v-moskve-bistro-i-nadezhno-4/

  25. You actually make it appear so easy with your
    presentation but I find this topic to be really one
    thing which I believe I might never understand. It kind of feels
    too complicated and very extensive for me. I’m looking forward for your subsequent
    post, I’ll attempt to get the cling of it!

  26. Cazrmix表示:

    Привет!
    Без ВУЗа очень непросто было продвигаться вверх по карьерной лестнице. На текущий момент документ не дает никаких гарантий, что удастся найти хорошо оплачиваемую работу. Более важны навыки специалиста и его постоянный опыт. В связи с этим решение о заказе диплома следует считать целесообразным. Приобрести диплом университета shoptema.ru/forum/topic/33574

發佈留言

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