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,123,433 Responses

  1. I do not even know the way I ended up right here, however I assumed this
    publish was good. I do not recognise who you are but certainly
    you’re going to a famous blogger for those who are not already.

    Cheers!

  2. The 9 Things Your Parents Taught You About Bunk Beds For Kids Bunk Beds For Kids

  3. Easydrorbix表示:

    viagra online pharmacy review: cytotec pharmacy online – viagra tesco pharmacy

  4. We’re a group of volunteers and starting a new scheme in our
    community. Your website provided us with valuable info to
    work on. You’ve done an impressive job and our whole community will be
    grateful to you.

  5. Easydrorbix表示:

    medicine online shopping: mexico pharmacy online – pharmacy vardenafil

  6. seo keywords表示:

    Greetings! I’ve been following your website for a while now and
    finally got the courage to go ahead and
    give you a shout out from Lubbock Tx! Just wanted to tell you keep up the
    fantastic job!

  7. Easydrorbix表示:

    kroger pharmacy tamiflu: provera online pharmacy – adipex online pharmacy

  8. link porno表示:

    What a data of un-ambiguity and preserveness of valuable
    familiarity about unpredicted feelings.

  9. Drstobeese表示:

    north american pharmacy viagra: flomax training pharmacy – pharmacy program online

  10. Cara Mahn表示:

    You said it adequately.!

  11. The 10 Most Terrifying Things About 3 Wheel Rollator Amazon 3 Wheel Rollator amazon

  12. Easydrorbix表示:

    finasteride online pharmacy: can you buy viagra at pharmacy – online pharmacy no rx

  13. How Adults ADHD Test Has Become The Most Sought-After Trend Of 2023 Adhd screening test (Private-Adhd-assessment48276.blogrelation.com)

  14. DouglasHoapy表示:

    Fonbet промокод https://fiesta-new.ru/wp-content/pgs/aktualnuy_promokod_fonbet_pri_registracii.html
    Fonbet предлагает разнообразные промокоды, которые предоставляют бонусы новым и существующим пользователям. Примером такого промокода является ‘GIFT200’, который активирует бесплатные ставки или другие бонусы. Использование промокодов делает игру на платформе более выгодной и увлекательной, предоставляя дополнительные преимущества пользователям.

  15. Drstobeese表示:

    hq pharmacy online 365: australian pharmacy domperidone – online pharmacy no perscription

  16. Easydrorbix表示:

    viagra in dubai pharmacy: voltaren online pharmacy – zovirax cream pharmacy

  17. get more info表示:

    Placing oneself on a self-exclusion list is completed in prescribed increments.

    My web page :: http://jonbian.co/getmoreinfo765802

  18. thor311表示:

    What’s up to every one, since I am actually keen of reading this webpage’s post to be updated daily.
    It consists of good material.

  19. website表示:

    Howdy! I could have sworn I’ve been to this website before
    but after going through many of the posts I realized
    it’s new to me. Anyways, I’m certainly delighted I discovered it and I’ll be book-marking
    it and checking back often!

  20. Gain full control of your documents with Scanner.biz!

    Turn your iPhone into a high-quality scanner
    with this app, digitizing papers, receipts, and notes in seconds.

    The app’s OCR technology allows for easy text extraction and editing from your scans.

    Organize your documents in custom folders and secure
    them with Face ID or a password.

    Share your documents immediately via email or cloud
    storage.

    Get Scanner.biz today and take control of your document
    management!

  21. Stephan表示:

    Electric Wheelchair With Joystick: 11 Things You’re Forgetting To
    Do 25 stone capacity electric wheelchair; Stephan,

  22. Easydrorbix表示:

    boots pharmacy antibiotic eye drops chloramphenicol: bactrim uk pharmacy – xenical mexican pharmacy

  23. Howdy! I know this is kind of off topic but I was wondering if you knew where I could get a captcha plugin for my comment form?

    I’m using the same blog platform as yours and I’m having difficulty finding one?
    Thanks a lot!

  24. Abrahamwarne表示:

    care rx specialty pharmacy: 15 rx pharmacy – online pharmacy lortab

  25. It’s amazing designed for me to have a site, which
    is valuable for my knowledge. thanks admin

  26. 11 Creative Ways To Write About Railroad Injuries Attorneys railroad worker Injuries

  27. 5 Car Unlock Service Projects For Any Budget Vehicle Lockout

發佈留言

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