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,467,155 Responses

  1. My spouse and I stumbled over here from a different web address and thought I
    should check things out. I like what I see so now i am following you.
    Look forward to looking at your web page for a second time.

  2. Excellent way of describing, and pleasant article to take information about my presentation subject, which i
    am going to present in college.

  3. I seriously love your site.. Great colors & theme.

    Did you make this site yourself? Please reply back as
    I’m looking to create my own personal blog and want
    to know where you got this from or just what the theme is called.
    Thank you!

  4. JasonUnsoG表示:

    http://sweetbonanza25.com/# sweet bonanza oyna

  5. Fantastic post! Discover more at drug detox omaha

  6. Aaron表示:

    Hi would you mind stating which blog platform
    you’re using? I’m going to start my own blog soon but I’m having a difficult
    time choosing between BlogEngine/Wordpress/B2evolution and Drupal.
    The reason I ask is because your design and style seems different then most blogs and I’m looking for something unique.
    P.S Sorry for being off-topic but I had to ask!

  7. Hey! Do you know if they make any plugins to protect against hackers?
    I’m kinda paranoid about losing everything I’ve worked hard on. Any suggestions?

  8. Ótimas dicas para manter os dentes saudáveis! Vou compartilhar com meus amigos e lembrá-los de visitar uma Limpeza dentária

  9. Deborah表示:

    Hi there! I could have sworn I’ve visited this website before but after going through a
    few of the articles I realized it’s new to me. Regardless, I’m definitely happy I stumbled upon it and I’ll be bookmarking it and checking back regularly!

  10. Hey just wanted to give you a quick heads up and let you know a
    few of the pictures aren’t loading correctly.
    I’m not sure why but I think its a linking issue. I’ve tried it in two different browsers and both show the
    same outcome.

  11. Howdy! I know this is kinda off topic but I’d figured I’d ask.
    Would you be interested in exchanging links or maybe guest authoring
    a blog post or vice-versa? My site goes over a lot of the same topics as yours and
    I feel we could greatly benefit from each other. If you happen to be interested feel free to send me an e-mail.
    I look forward to hearing from you! Superb blog by the way!

  12. Scottmeali表示:

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

  13. useful source表示:

    I am really loving the theme/design of your web site. Do you ever run into any
    web browser compatibility problems? A number of my blog readers have complained about my site not working correctly in Explorer but looks great in Safari.
    Do you have any advice to help fix this problem?

  14. Lois Bowers表示:

    “Is there anything that # anykeyword# can’t fix? They seem to h iphone repair

  15. Etta Hardy表示:

    Bounce homes are perfect for every ages! We rented one for my child’s graduation party, and also the adults delighted in jumping about water bounce house rental

  16. I like it when individuals get together and
    share ideas. Great site, keep it up!

  17. Esther Hodges表示:

    I’m curious about the average timeline for getting approved by a Tacoma mortgage lender. Any insights? I found some useful timelines at Home Loans Tacoma

  18. Fantastic goods from you, man. I’ve keep in mind your stuff previous to and you’re simply too great.
    I actually like what you have bought here, really like
    what you’re saying and the best way by which you say it.
    You’re making it entertaining and you continue to take care
    of to keep it sensible. I can’t wait to read much more from you.

    That is really a terrific site.

  19. Dannyfut表示:

    darkmarket url tor marketplace black internet

  20. Wallacefex表示:

    sweet bonanza giris: sweet bonanza slot – sweet bonanza guncel

  21. BradleyEdino表示:

    sweet bonanza guncel sweet bonanza slot sweet bonanza giris

  22. In recent years, Cannabidiol (order Sunburst CBD) has gained
    significant traction in the wellness and health industry, celebrated for its potential
    benefits.

  23. Wow, superb blog layout! How long have you been blogging for?

    you made blogging look easy. The overall look of your web
    site is excellent, let alone the content!

  24. despite the fact that Bitcoin has been developing since
    2009, https://kekius-maximus.vip/
    and applications technologies blockchain still
    appear in monetary equivalent, and in future more/more applications of cryptocurrencies are expected.

  25. JasonUnsoG表示:

    https://slotsiteleri25.com/# slot siteleri

  26. Nell Wolfe表示:

    This was a wonderful post. Check out pest control all india pest control andheri for more

  27. Jump houses are ideal for all ages! We leased one for my little girl’s college graduation party, and even the adults enjoyed jumping about adult bounce house rental

  28. Jeannie表示:

    24 Hours To Improving SEO Tools software for
    seo (Jeannie)

  29. Have you ever tried pressing blossoms? It’s a beautiful means to preserve their charm! I share my favored techniques at affordable flowers san francisco delivery

發佈留言

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