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,233,188 Responses

  1. 5 Killer Quora Answers To Link Togel Resmi link togel resmi

  2. Hello, of course this piece of writing is genuinely nice and I have learned
    lot of things from it concerning blogging. thanks.

  3. The Top Reasons For Hyundai Tucson Key Replacement’s Biggest “Myths” About
    Hyundai Tucson Key Replacement Could Be True hyundai elantra keys Locked in car

  4. Wonderful, what a web site it is! This website provides valuable data to us, keep it up.

  5. Trefijx表示:

    Парадокс, но купить диплом кандидата наук оказалось не так и сложно

    etoprosto.ru/ru/forum/?category=5&action=topic

  6. ClydePab表示:

    Canl? Casino Siteleri: Casino Siteleri – Casino Siteleri

  7. LarryCoell表示:

    az parayla cok kazandiran slot oyunlar? en cok kazand?ran slot oyunlar? slot tr online

  8. 10 Things You Learned In Kindergarden Which Will Aid You In Obtaining Sectional Sofas For Sale
    leather Sofas for sale Near me (morphomics.science)

  9. Greetings! Quick question that’s completely off topic.
    Do you know how to make your site mobile friendly? My site looks weird when browsing
    from my iphone4. I’m trying to find a theme or plugin that might be able to resolve
    this problem. If you have any suggestions, please share.
    Cheers!

  10. 20 Trailblazers Lead The Way In Leather Sectional Sleeper Sofa Leather Sleeper Sectional

  11. When I initially commented I clicked the “Notify me when new comments are added” checkbox
    and now each time a comment is added I get four emails with the same comment.
    Is there any way you can remove people from that service?
    Bless you!

  12. ClydePab表示:

    Casino Siteleri: Canl? Casino Siteleri – casino siteleri win

  13. The Most Common Mistakes People Make With Upvc Windows
    Repairs repairing upvc Windows

  14. Trefpwv表示:

    Быстрое обучение и получение диплома магистра – возможно ли это?
    bn.tobase.ru/posting.php?mode=post&f=30&sid=eeb549e4ef66822700e8cfa6ebe8a4d3

  15. Trefvte表示:

    Пошаговая инструкция по официальной покупке диплома о высшем образовании

    11sms.ru/?post_type=topic&p=7976

  16. Sazrhbk表示:

    Как оказалось, купить диплом кандидата наук не так уж и сложно
    szanuj-sie.pl/forum/viewtopic.php?f=6&t=37021

  17. LarryCoell表示:

    deneme bonusu veren siteler yeni denemebonusuverensiteler.top deneme bonusu veren siteler yerliarama.org

  18. CarrollUnton表示:

    deneme bonusu veren siteler betturkey https://denemebonusuverensiteler.top/# deneme bonusu veren siteler mycbet.com

  19. Sazrvzg表示:

    Полезные советы по безопасной покупке диплома о высшем образовании
    khvoynaya.getbb.ru/viewtopic.php?f=39&t=7475

  20. Ten Common Misconceptions About Mitsubishi Lost Key Replacement That Aren’t Always The Truth Mitsubishi key replacement; https://Telegra.ph,

  21. DwightDAURI表示:

    Get pill info. Latest medication developments.
    best online pharmacies
    Medication reactions explained. Find medicine info.

  22. You really make it appear so easy with your presentation but I
    to find this topic to be really one thing that I feel I might never understand.
    It sort of feels too complicated and extremely large for me.
    I am taking a look ahead to your next submit, I’ll
    try to get the dangle of it!

  23. If you are going for best contents like myself, just pay a visit
    this website all the time as it presents quality contents, thanks

  24. Trefbvo表示:

    Официальная покупка диплома вуза с сокращенной программой обучения в Москве
    ukrevent.ru/kupit-diplom-s-garantiey-kachestva

  25. LarryCoell表示:

    deneme bonusu veren siteler deneme bonusu veren yeni siteler deneme bonusu veren siteler yerliarama.org

  26. Great post. I will be dealing with a few of these issues as well..

  27. ClydePab表示:

    matadorbet: matadorbet giris – matadorbet.bid

發佈留言

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