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,248,408 Responses

  1. Great insights on optimizing websites for legal firms! It’s essential to adapt SEO strategies for the legal industry seo for lawyers

  2. Lelia Lambert表示:

    Great advice shared regarding using local events or sponsorships as avenues towards networking opportunities beneficially building relationships throughout communities through seo for lawyers

  3. Loved how you addressed balancing workloads amongst attorneys while ensuring each member feels valued contributing overall success towards growth initiatives moving forward through marketing agency for law firms

  4. Hulda Bowers表示:

    When’s the best season to install a new roof tile repair

  5. Just wanted to say how essential it is to use quality materials; they make all the difference in longevity roofers

  6. I recently had my roof replaced, and it made such a difference in my home’s appearance roofing companies

  7. The connection between branding and effective SEO cannot be overstated! Check out more information available at seo company for lawyers

  8. The importance of ventilation systems in roofs can’t be stressed enough; thanks for highlighting that issue here! roofing contractor

  9. Fannie Nguyen表示:

    I appreciate all the insights shared focusing upon building relationships beyond transactional interactions fostered organically creating lasting partnerships yielding tremendous value extending beyond immediate concerns henceforth local seo law firm

  10. Cl-System.jp表示:

    Thanks for ones marvelous posting! I truly enjoyed reading
    it, you might be a great author.I will make certain to bookmark your blog and definitely will come
    back in the future. I want to encourage you
    continue your great writing, have a nice weekend! https://Cl-System.jp/question/conseils-pour-un-demenagement-professionnel-reussi-simplifiez-votre-transition-sur-ces-astuces-pratiques-7/

  11. Mamie Becker表示:

    Great insights on roofing! I always recommend checking professional services before starting any project residential roofers

  12. RhodaReN表示:

    nomini casino bietet eine spannende und bequeme Möglichkeit, Ihre Lieblingsspiele bequem von zu Hause aus zu genießen. Mit einer großen Auswahl an Optionen können Sie jederzeit und überall Casino-Klassiker wie Poker, Blackjack und Spielautomaten spielen. Online-Casinos bieten ein spannendes Spielerlebnis mit realistischer Grafik und Live-Dealer-Optionen. Tauchen Sie noch heute in die Welt der online casinos ein und erleben Sie die Aufregung und die Vorteile des virtuellen Spielens Ihrer Lieblingsspiele.

  13. Jerryrulty表示:

    Casino is not just a game of luck; it’s a thrilling challenge that can be mastered with the right strategy. Imagine the excitement of hitting 21 and beating the dealer with confidence. Whether you’re a novice or an experienced player, learning gambling bets online can transform your gaming experience and lead to significant wins. Don’t miss out on the opportunity to improve your skills and enjoy the rewards. Start playing blackjack today and take the first step towards becoming a pro!

  14. Louissuext表示:

    Drug leaflet here. Latest medication news.
    buy proscar with no prescription
    Latest drug developments. Drug essentials explained.

  15. A friend just had their old roof replaced with a sleek black metal finish, and it looks incredible! See similar styles at metal roofing

  16. BrandenSlomy表示:

    amoxicillin online without prescription: Com Pharm – where can i get amoxicillin 500 mg

  17. Nikefut表示:

    best darknet markets tor darknet https://darknetmarketstore.com/ – tor darknet

  18. brianclub表示:

    It’s hard to find educated people for this topic, but you seem like
    you know what you’re talking about! Thanks

    Here is my homepage – brianclub

  19. StevenNub表示:

    amoxicillin 500mg capsule: amoxil – order amoxicillin 500mg

  20. Hello there! This is my 1st comment here
    so I just wanted to give a quick shout out and tell you I genuinely enjoy reading through your posts.
    Can you recommend any other blogs/websites/forums
    that go over the same topics? Thank you
    so much!

  21. StevenNub表示:

    where to buy amoxicillin: amoxicillin generic brand – can i purchase amoxicillin online

  22. 주소주라表示:

    How To Use Your Facebook 주소주라

  23. BrandenSlomy表示:

    prednisone buy online nz: order Prednisone – buy prednisone 10 mg

  24. I have read several excellent stuff here. Definitely value bookmarking for revisiting.
    I surprise how so much effort you place to make such a wonderful informative web site.

  25. Matilda Young表示:

    Appreciate the great suggestions. For more, visit Best Locksmith Near Me

  26. BrandenSlomy表示:

    80 mg prednisone daily: prednisone 10 mg tablet – prednisone 10mg price in india

發佈留言

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