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,231,060 Responses

  1. Treat Generalized Anxiety Disorder Tips From The Most Effective In The Industry anxiety disorder treatment without Medication

  2. These are really great ideas in on the topic of blogging.
    You have touched some good factors here. Any way keep
    up wrinting.

  3. HassanbuifS表示:

    https://matadorbet.bid/# matadorbet
    deneme bonusu veren siteler 2024

  4. Diplomi_qukn表示:

    купить диплом о среднем специальном недорого 1russa-diploms.ru .

  5. If you wish for to obtain a great deal from this piece of writing then you have
    to apply such techniques to your won web site.

  6. Why You’ll Need To Find Out More About Online Mystery Boxes mystery Boxes Best

  7. Fridge Freezer With Water Dispenser And Ice Maker Explained
    In Less Than 140 Characters Water dispensing fridge Freezer

  8. LarryCoell表示:

    matadorbet matadorbet giris matadorbet.bid

  9. Тут можно преобрести сейф огнестойкий купить огнестойкие сейфы цена

  10. We stumbled over here different page and thought
    I may as well check things out. I like what I see so now i’m following you.
    Look forward to exploring your web page for a second time.

    https://datasgp.icu/

  11. ClydePab表示:

    ultrabet tr online: ultrabet tr online – ultrabet yeni giris 1125

  12. promo code表示:

    Its like you read my mind! You seem to grasp a lot approximately this, like you wrote the guide in it or something.
    I think that you simply could do with a few % to force the message house
    a bit, however instead of that, that is fantastic blog.
    A fantastic read. I’ll definitely be back.

  13. ArnPaish表示:

    more information on erectile dysfunction, visit our website at ivermectin covid at cheap prices after comparing offers

  14. aiporn.loan表示:

    I think this is one of the so much important info for me.
    And i’m happy reading your article. However wanna remark on few common issues, The website taste is great, the articles
    is truly great : D. Good activity, cheers

  15. posteezy.com表示:

    Everything You Need To Be Aware Of Cut Car Keys vw key cut by Vin near me – posteezy.com

  16. Bruceviomy表示:

    Ведь есть же десятки сервисов для номеров из других стран. А беларусские форумы огорожены, им подавай только их собственный картофель типа +375 купить временный номер телефона

  17. ClydePab表示:

    matadorbet: matadorbet – matadorbet

  18. Derekfar表示:

    matadorbet giris: matadorbet bid – matadorbet.bid

  19. Sazrruh表示:

    Пошаговая инструкция по официальной покупке диплома о высшем образовании
    plyushki.flybb.ru/viewtopic.php?f=6&t=621

  20. Excellent goods from you, man. I have be aware your stuff prior to and you are just extremely fantastic.
    I actually like what you have obtained here, certainly like what you’re stating and the way by which you say
    it. You make it entertaining and you continue to care for to keep it wise.
    I can’t wait to learn far more from you. This is actually a wonderful website.

    https://ww1.prediksisyair.buzz/

  21. It’s not my first time to pay a quick visit this web site, i am visiting
    this web site dailly and take pleasant information from here every day.

    Take a look at my web page – เช่าชุดเจ้าสาว

  22. Sazrqon表示:

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

    kvitka.ukrbb.net/viewtopic.php?f=58&t=27334

  23. Derekfar表示:

    guvenilir casino siteleri: Casino Siteleri – guvenilir casino siteleri

  24. Тут можно преобрести огнеупорный сейф купить купить сейф огнестойкий в москве

  25. Diplomi_ibMl表示:

    купить диплом уральского many-diplom77.ru .

  26. Stephenideox表示:

    Окунитесь в течение мир веселий а также интересных историй на портале Эрот 28!
    юбилей

發佈留言

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