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,524,209 Responses

  1. MichaelIncap表示:

    drug markets onion https://github.com/darknetmarketslinks/darknetmarketlinks – darknet market links tor darknet

  2. BTC Pro ePrex表示:

    Hello there, You’ve done a great job. I will definitely digg
    it and personally suggest to my friends. I am confident they will be benefited from this web site.

  3. MichaelIncap表示:

    deep dark web https://github.com/darknetmarketslinks/darknetmarketlinks – darkweb marketplace darknet drug links

  4. betflix282表示:

    You are so awesome! I do not suppose I’ve truly read a single thing like
    that before. So good to find somebody with a few original
    thoughts on this subject. Seriously.. many thanks for starting this
    up. This site is something that is required on the web, someone with a little originality!
    betflix282

  5. Medicament information. Generic Name.
    finasteride y musculatura
    Actual trends of medicine. Read here.

  6. Contoh CV表示:

    Hi there, I discovered your website by means of Google
    while looking for a similar topic, your site got here up, it seems to
    be great. I have bookmarked it in my google bookmarks.

    Hi there, simply became alert to your weblog
    through Google, and found that it’s really informative.
    I’m going to watch out for brussels. I’ll appreciate
    in case you proceed this in future. A lot of other people will probably be benefited out
    of your writing. Cheers!

  7. MichaelIncap表示:

    deep web drug markets https://github.com/darknetmarketslinks/darknetmarketlinks – dark web market black internet

  8. MarkWat表示:

    Всем привет! Подскажите, где почитатьполезные блоги о займах? Пока нашел – allrekords.ru

  9. 7 Easy Secrets To Totally Rocking Your Pallet Prices Pallet Prices

  10. скачать взломанные игры на андроид без регистрации — это интересный способ повысить качество игры.
    Особенно если вы играете на Android, модификации открывают перед
    вами широкие горизонты. Я лично использую игры с обходом системы защиты,
    чтобы получать неограниченные ресурсы.

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

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

    Рекомендую попробовать такие модифицированные
    версии для Android — это может придаст новый смысл

  11. How Online Casinos Are So Popular

    Digital casinos have modernized the gaming market, offering a unique kind of user-friendliness and variety that physical establishments fall short of. Recently, millions of players internationally have adopted the fun of digital casino play as a result of its always-open nature, engaging traits, and constantly growing catalogs of games.

    One of the strongest selling points of internet-based platforms is the astounding array of entertainment options on offer. Whether you enjoy spinning traditional fruit machine slots, immersing yourself in plot-filled video slots, or strategizing in strategy-based games like Blackjack, digital casinos deliver numerous possibilities. Numerous services furthermore present interactive dealer games, making it possible for you to communicate with live hosts and opponents, all while immersing yourself in the realistic ambiance of a brick-and-mortar establishment from anywhere you want.

    If you’re just starting with the world of virtual casino play or would like to learn about proven options, why not become part of our growing gaming forum? It’s a platform where enthusiasts discuss reviews, guiding you to get the most out of your online casino experience. Check out the connections and start your journey now: 22bet è legale in italia

    Adding to the extensive catalog, online casinos thrive in accessibility.

  12. Davidmoits表示:

    top 10 online pharmacy in india: MegaIndiaPharm – online shopping pharmacy india

  13. MarkWat表示:

    Привет. Подскажите, где почитатьполезные блоги о кредитах? Сейчас читаю – https://123inv.ru

  14. polythene表示:

    I believe what you wrote made a bunch of sense.
    However, think on this, what if you typed a catchier title?
    I ain’t suggesting your information isn’t good, however what if you added
    a headline that makes people desire more? I mean JS 依照元素出現數量排序
    – 馬老師 雲端研究室 is kinda plain. You could peek at Yahoo’s front page and
    watch how they create news titles to grab people to open the links.
    You might add a related video or a related pic or two
    to grab readers interested about everything’ve written. In my opinion, it
    might make your posts a little livelier.

    Here is my homepage … polythene

  15. Porterfax表示:

    xxl mexican pharm reputable mexican pharmacies online xxl mexican pharm

  16. Facing financial hardship? struggling to keep up with rent payments can be a terrifying
    experience. Thankfully, Riverside offers numerous resources available to help residents in need.
    A multitude of organizations and programs stand ready to assist, ensuring no one faces eviction alone.

  17. This expense may be particularly high if you’re upgrading to an electric tankless
    model.

  18. 20 Tools That Will Make You Better At Tunnel Containers 40ft tunnel containers (writeablog.Net)

  19. Rodneytus表示:

    deep web drug links https://github.com/darkwebmarketslinks/darkwebmarkets – darknet market darknet drugs

  20. WillieRap表示:

    xxl mexican pharm: xxl mexican pharm – xxl mexican pharm

  21. Rodneytus表示:

    tor marketplace https://github.com/darkwebmarketslinks/darkwebmarkets – darknet market dark web sites links

  22. WillieRap表示:

    discount drugs: discount drugs – drug mart

  23. Charleskepsy表示:

    buying prescription drugs from canada https://discountdrugmart.pro/# discount drug mart pharmacy

  24. WillieRap表示:

    cheapest pharmacy to fill prescriptions without insurance: Best online pharmacy – family pharmacy

  25. MarkWat表示:

    Всем привет! Может кто знает, где найтиполезные блоги о займах? Сейчас читаю – lombard-club.ru

  26. Could Assessment Of Psychiatric Patient Be The Key For 2024’s Challenges?
    Free Psychiatric Assessment

  27. Davidnof表示:

    dark web sites https://github.com/darkwebwebsites/darkwebwebsites – dark web markets dark net

  28. Davidmoits表示:

    MegaIndiaPharm: indian pharmacies safe – MegaIndiaPharm

發佈留言

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