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,247,059 Responses

  1. Im thankful for the creative and insightful content you provide on this platform.
    Tahun Baru Slot 2025

  2. DarrenUnjuh表示:

    https://cytpremium.com/# buy cytotec pills

  3. I am incredibly thankful for the consistent quality of content on this blog.
    Memilih Rtp Gacor

  4. I am incredibly thankful for the consistent quality of content on this blog.
    Pasang Togel Macau

  5. BrandenSlomy表示:

    where can i get cheap clomid price: where to get cheap clomid without a prescription – can i buy clomid without insurance

  6. AlbertDuM表示:

    Misoprostol 200 mg buy online: cheapest cytotec – п»їcytotec pills online

  7. If you’re thinking about a roof upgrade, have you thought about energy-efficient options? It can help in reducing your bills! I found out a lot from checking out articles on roofer in tampa relating to environmentally friendly roofing options

  8. Pretty section of content. I just stumbled upon your website and in accession capital to assert that I
    acquire actually enjoyed account your blog posts.
    Anyway I’ll be subscribing to your feeds and even I achievement you access consistently rapidly.

  9. Harvey表示:

    What Is The Reason? Good Infant Car Seats Is Fast Becoming The Hottest Trend Of 2024 best infant car seat (Harvey)

  10. What a data of un-ambiguity and preserveness of precious know-how about unpredicted emotions.

  11. DarrenUnjuh表示:

    https://lisinopril1st.com/# cheapest Lisinopril

  12. Signature Drinks 유흥사이트 (Freeflashgamesnow.Com)

  13. Kolyaska_zePl表示:

    Идеальная коляска Bugaboo для вашего малыша, Bugaboo: лучшее решение для малыша и родителей, Почему мамы выбирают коляски Bugaboo, Какие преимущества у колясок Bugaboo, Bugaboo – это качество и надежность, Какая коляска Bugaboo подойдет вашей семье, Bugaboo Bee: стиль и удобство для малыша, Bugaboo Buffalo: коляска для любых приключений.
    bugaboo ant цена bugaboo ant цена .

  14. These platforms allow unfiltered access to slot features Bonus
    Buy, Quickspin and Autoplay.

  15. Howdy superb blog! Does running a blog similar to this require a great deal of
    work? I have no knowledge of programming however I had been hoping to start my own blog in the near future.

    Anyways, if you have any ideas or techniques for new
    blog owners please share. I understand this is off subject
    but I simply needed to ask. Appreciate it!

  16. Fantastic beat ! I would like to apprentice while you amend your site, how can i subscribe for a blog web site?
    The account helped me a acceptable deal. I had been a
    little bit acquainted of this your broadcast offered bright clear idea

  17. I’ve been browsing online more than 4 hours today, yet I never found any interesting article like yours.
    It is pretty worth enough for me. In my view, if all
    webmasters and bloggers made good content as you did,
    the net will be a lot more useful than ever before.

  18. jual organ表示:

    Please let me know if you’re looking for a writer for your weblog.
    You have some really good posts and I believe
    I would be a good asset. If you ever want to take some of the load off, I’d really
    like to write some articles for your blog in exchange for a link back to mine.
    Please blast me an email if interested. Thank you!

  19. Pills information sheet. Long-Term Effects.
    cost of generic paxil pill
    Best news about medicine. Get information here.

  20. Every weekend i used to visit this website, because i want enjoyment, since this this site conations truly nice
    funny information too.

  21. Its like you read my mind! You appear to know a
    lot about this, like you wrote the book in it
    or something. I think that you can do with a few
    pics to drive the message home a little bit, but instead of that,
    this is magnificent blog. An excellent read. I will certainly be back.

    Also visit my blog; timbangan Semarang – http://www.tumblr.com,

  22. Blakesmema表示:

    кухня на заказ екатеринбург недорого — Кухни высокого качества по доступным ценам в Екатеринбурге.

  23. What Private ADHD Assessments Experts Want You To Know?
    private adhd assessment glasgow cost

  24. BernardMop表示:

    Cytotec 200mcg price buy cytotec online Cytotec 200mcg price

  25. Excellent article on roof inspections! Regular checks can save homeowners a lot of money. For more tips on maintaining your roof, head over to Roofing Company in Houston

發佈留言

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