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,366,021 Responses

  1. Laskar303表示:

    Ι tһink the admin of this website iѕ aϲtually ѡorking hɑгԀ іn favor of
    hiѕ site, since һere every іnformation is quality based material.

    Feel frere t᧐ surf to mʏ homepage: Laskar303

  2. BrandenSlomy表示:

    medicine prednisone 10mg: order Prednisone – canada pharmacy prednisone

  3. This is really interesting, You’re a very skilled
    blogger. I’ve joined your feed and look forward to seeking more of your wonderful post.
    Also, I have shared your website in my social networks! https://monroyhives.biz/author/jamisonboun/

  4. I quite like looking through an article that will make
    men and women think. Also, thank you for permitting me
    to comment!

  5. Top Money Making Apps in Pakistan, Top Money Making Apps in Pakistan and Their Features
    top 10 earning apps in pakistan earn money app in pakistan .

  6. forkpart.ru表示:

    На сайте forkpart.ru можно приобрести шинокомплект погрузчика, который отвечает всем стандартам безопасности и долговечности. Мы знаем, насколько важны качественные шины для бесперебойной работы техники, поэтому предлагаем только проверенные решения. В каталоге представлены модели для различных типов погрузчиков, с учетом их специфики. Мы гарантируем конкурентоспособные цены и оперативное обслуживание. Убедитесь в этом сами — сделайте заказ на нашем сайте!

  7. Shane Cortez表示:

    This was highly useful. For more, visit Roofing Contractor Seattle

  8. Wow, wonderful 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!

  9. BrandenSlomy表示:

    cheap priligy: dapoxetine price – dapoxetine price

  10. Nikefut表示:

    darknet markets darknet sites https://darknetmarketstore.com/ – dark market url

  11. Medication prescribing information. Effects of Drug Abuse.
    where to buy generic singulair for sale
    Best news about meds. Get information now.

  12. Dereketerm表示:

    can i buy prednisone online without a prescription: prednisone – prednisone 2.5 mg

  13. Dereketerm表示:

    amoxicillin 200 mg tablet: com pharm – cost of amoxicillin prescription

  14. BrandenSlomy表示:

    amoxicillin online without prescription: Amoxicillin for sale – generic amoxicillin over the counter

  15. вызов нарколога на дом круглосуточно http://www.masa.forum24.ru/?1-16-0-00002626-000-0-0-1730730156/ .

  16. ariat slippers women’s square toe

    Your style is so unique compared to other folks I’ve read stuff from.
    Thanks for posting when you’ve got the opportunity, Guess I’ll just bookmark this site.

  17. LamarFob表示:

    Comprehensive drug facts. Medication resource available.
    buy proscar 5 mg
    Pill information available. Pill guide available.

  18. CuanToto表示:

    I constɑntly spent my half ɑn hour to read thiѕ webpage’s articles or reviews ɑll the time аlong ᴡith а
    muց ߋf coffee.

    Aⅼso viisit my website … CuanToto

  19. Casino表示:

    You really make it appear so easy together with your presentation however I in finding this
    matter to be actually something which I believe I’d by no means
    understand. It sort of feels too complicated and extremely huge for me.
    I am looking ahead in your next put up, I’ll try to
    get the hang of it!

發佈留言

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