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,453,575 Responses

  1. Think You’re Ready To Start Doing Electric Patio Heater?
    Answer This Question Best electric patio heaters Uk (Opensourcebridge.science)

  2. Carrolleruck表示:

    https://canadianmdpharm.com/# northwest pharmacy canada
    canadian pharmacy 24h com safe

  3. zaramea01表示:

    When someone writes an paragraph he/she maintains
    the thought of a user in his/her brain that how a user can know it.
    Thus that’s why this article is perfect. Thanks!

    My blog post zaramea01

  4. Thank you for the auspicious writeup. It in fact was a amusement account it.
    Look advanced to more added agreeable from you!
    However, how can we communicate? http://Onestopclean.kr/bbs/board.php?bo_table=free&wr_id=602969

  5. CurtisBam表示:

    Online medicine: Indian pharmacy that ships to usa – IndianCertPharm

  6. CurtisBam表示:

    legitimate canadian mail order pharmacy: CanadianMdPharm – canadian pharmacy

  7. CurtisBam表示:

    safe canadian pharmacy: Canadian Md Pharm – best canadian pharmacy online

  8. 3 Ways The Buy Driver’s License Online Influences Your Life köP Körkort B96 utan examen Online

  9. Wow that ԝaѕ strange. Ι just wrote an extremely ⅼong
    comment but after I ϲⅼicked submit my comment didn’t show up.
    Grrrr… ᴡell I’m not writing aⅼl that over again. Anyhow, just wanted to
    say great bⅼog!

    my blog :: uniform store Near me

  10. Brandonnot表示:

    pet meds without vet prescription canada: Canadian Md Pharm – northwest canadian pharmacy

  11. I’ve read some just right stuff here. Certainly price bookmarking for revisiting.

    I wonder how so much effort you place to make this sort of magnificent informative site.

  12. id=”firstHeading” class=”firstHeading mw-first-heading”>Search results

    Help

    English

    Tools

    Tools
    move to sidebar hide

    Actions

    General

  13. hello there and thank you for your info – I have definitely
    picked up anything new from right here. I did however expertise some technical points using this site, as I experienced to reload the site lots of times previous to I could get it to load correctly.
    I had been wondering if your web host is OK? Not that I am complaining,
    but sluggish loading instances times will sometimes affect your placement in google and can damage
    your quality score if ads and marketing with Adwords.
    Anyway I am adding this RSS to my email and could look out for much more of your respective fascinating
    content. Make sure you update this again soon.

  14. viking salt表示:

    Your method of explaining everything in this article is
    genuinely nice, every one be able to effortlessly know
    it, Thanks a lot.

  15. Brandonnot表示:

    Indian Cert Pharm: IndianCertPharm – Indian pharmacy international shipping

  16. MichaelUntot表示:

    not working
    _________________
    Best online casino

  17. Brandonnot表示:

    canadian pharmacy 24h com: CanadianMdPharm – canada online pharmacy

  18. MichaelUntot表示:

    Thanks for the post
    _________________
    Best online casino

  19. CurtisBam表示:

    buying prescription drugs in mexico online: Mexican Easy Pharm – medicine in mexico pharmacies

  20. CurtisBam表示:

    Mexican Easy Pharm: medicine in mexico pharmacies – mexican online pharmacies prescription drugs

  21. Brandonnot表示:

    Indian pharmacy that ships to usa: IndianCertPharm – Best online Indian pharmacy

  22. wonderful points altogether, you just won a new reader. What could you suggest in regards to your put up
    that you made some days in the past? Any sure?

  23. Предлагаем услуги профессиональных инженеров офицальной мастерской.
    Еслли вы искали ремонт iphone se 2020 адреса, можете посмотреть на сайте: ремонт iphone se 2020
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

發佈留言

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