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,244,855 Responses

  1. Markdob表示:

    Всем привет! Может кто знает, где найтиразные блоги о недвижимости? Сейчас читаю – https://credomir.ru

  2. Узнай все о двустороннее варикоцеле клиника варикоцеле

  3. Dereketerm表示:

    buying generic clomid tablets: clomid – can i purchase cheap clomid no prescription

  4. Lazrrke表示:

    Аттестат школы купить официально с упрощенным обучением в Москве

    2cool.ru/qiwi-f215/oformite-diplom-za-schitannie-dni-i-nachnite-rabotat-zavtra-t4380.html

  5. Markdob表示:

    Приветствую. Подскажите, где найтиполезные блоги о недвижимости? Сейчас читаю – https://credomir.ru

  6. This Week’s Most Popular Stories About Automatic Folding Travel Mobility Scooter Automatic Folding Travel Mobility Scooter auto folding travel Scooter

  7. Тут можно преобрести оружейный сейф купить москва оружейный сейф для ружья

  8. Angelita表示:

    You really make it seem so easy with your presentation but
    I find this matter to be actually something
    which I think I would never understand. It seems too complicated and
    very broad for me. I am looking forward for your next post, I’ll try to
    get the hang of it!

  9. Lazroyp表示:

    Всё, что нужно знать о покупке аттестата о среднем образовании без рисков

    knigiok.ru/?post_type=topic&p=28351

  10. Nikefut表示:

    dark net darkmarket dark website

  11. BrandenSlomy表示:

    dapoxetine online: priligy max pharm – buy priligy max pharm

  12. BrandenSlomy表示:

    medicine amoxicillin 500mg: Com Pharm – amoxicillin online no prescription

  13. Medicines information leaflet. What side effects can this medication cause?
    side effects of hydroxyzine hcl 50mg
    Everything what you want to know about drug. Get information here.

  14. bookmarked!!, I love your website!

  15. StevenNub表示:

    amoxicillin cephalexin: Amoxicillin Com Pharm – amoxicillin capsule 500mg price

  16. Узнай все о варикоцеле яичка варикоцеле 2 степени

  17. BrandenSlomy表示:

    amoxicillin 500 mg tablets: Amoxicillin Com Pharm – generic amoxicillin 500mg

  18. Lazrrwq表示:

    Официальная покупка диплома вуза с упрощенной программой обучения

    1001vieclam.forumvi.com/login

  19. Blakesmema表示:

    mptextile.ru/ — Качественные кухни на заказ от профессионалов.

  20. BrandenSlomy表示:

    where can i buy clomid prices: rexpharm – can i purchase generic clomid online

  21. Dereketerm表示:

    otc prednisone cream: prednisone 10 tablet – prednisone tablets 2.5 mg

  22. Fluxion Oil表示:

    Very good information. Lucky me I ran across your website by accident (stumbleupon).
    I have saved it for later!

  23. Casino表示:

    I seriously love your website.. Pleasant colors & theme. Did you make this website yourself?
    Please reply back as I’m wanting to create my own site and want to find out where you got this
    from or exactly what the theme is called. Kudos!

  24. Reliable info Thank you!

  25. Nikefut表示:

    darkmarket link dark market dark web market list

發佈留言

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