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,238,070 Responses

  1. Derekfar表示:

    ultrabet bonus: ultrabet giris – ultrabet tr online

  2. Is Your Company Responsible For The Buy Espresso Machine Budget?
    12 Best Ways To Spend Your Money Uk Espresso Machine

  3. sarang188表示:

    excellent put up, very informative. I wonder why the opposite specialists of this sector do not realize
    this. You should continue your writing. I’m sure, you’ve
    a great readers’ base already!

  4. LarryCoell表示:

    Deneme Bonusu Veren Siteler Deneme Bonusu Veren Siteler Casino Siteleri

  5. You’ll Never Guess This All Terrain Folding Electric Wheelchair Uk’s
    Benefits All Terrain Folding Electric Wheelchair; Syriasquash7.Werite.Net,

  6. I got this web site from my pal who told me concerning
    this web site and now this time I am visiting this website and
    reading very informative posts here.

  7. It’s Time To Expand Your Private ADHD Assessment Near
    Me Options Private adhd assessment wales cost (tornadosocial.com)

  8. 匿名訪客表示:

    Do you have a spam issue on this site; I also am a blogger, and I
    was curious about your situation; we have created some nice practices and we are looking to swap strategies with other folks, be sure to shoot
    me an email if interested.

  9. Diplomi_nfer表示:

    купить диплом с проводкой купить диплом с проводкой .

  10. CarrollUnton表示:

    deneme bonusu veren siteler yerliarama.org https://slot-tr.online/# az parayla cok kazandiran slot oyunlar?

  11. ClydePab表示:

    deneme bonusu veren siteler yerliarama.org: denemebonusuverensiteler.top – deneme bonusu veren siteler betturkey

  12. Derekfar表示:

    deneme bonusu veren siteler: deneme bonusu veren yeni siteler – deneme bonusu veren siteler betturkey betturkey.com

  13. WordPress GPL Themes / GPL Plugins The most complete cracking plugin/theme store on the market, with a total website of nearly 20000+ Ensure that the product has no backdoors and is safe to use Search for the desired products directly in English. The English search should be purposeful

  14. ClydePab表示:

    slot oyunlar? puf noktalar?: slot tr online – en kazancl? slot oyunlar?

  15. Medicament information. Effects of Drug Abuse.
    cymbalta duloxetine weight loss
    Everything about medicines. Get now.

  16. Derekfar表示:

    slot oyunlar?: slot tr online – slot siteleri

  17. whoah this blog is magnificent i really like studying your
    posts. Keep up the good work! You already know, a lot of people are searching around for this
    information, you could help them greatly.

  18. Diplomi_drer表示:

    аттестат школьный купить аттестат школьный купить .

  19. Diplomi_user表示:

    купить диплом мгуп prema365-diploms.ru .

  20. PhillipRalty表示:

    Разработка сайтов на платформе 1С-Битрикс в студии в Москве включает полный цикл: от проектирования до запуска и дальнейшего сопровождения. Также предлагаются услуги: оптимизация сайта для поисковых систем, интеграция с хостингом, контентное наполнение, анализ данных и маркетинговые стратегии https://Webstudiya-Moscow.ru/

  21. LarryCoell表示:

    deneme bonusu veren siteler yeni deneme bonusu veren siteler betturkey deneme bonusu veren siteler 2024

  22. Your way of telling the whole thing in this post is actually nice,
    every one be capable of without difficulty be aware of it, Thanks
    a lot https://logosportqc.com/

  23. Its like you read my mind! You seem to know a lot about this,
    like you wrote the book in it or something. I think that you
    can do with a few pics to drive the message
    home a little bit, but instead of that, this is great blog.
    A great read. I will definitely be back.

  24. Geraldvef表示:

    Разработка лендингов в студии в Москве осуществляется с учетом современных маркетинговых стратегий и требований рынка. К основным услугам добавляются: аудит и анализ конверсии, продвижение в поисковых системах, контентное наполнение, настройка CRM и профессиональная техническая поддержка создание лендинг страницы

  25. 7 Practical Tips For Making The Profits Of Your Mystery Box open mystery boxes online

  26. Hello to every body, it’s my first go to see of this webpage; this blog contains amazing and actually excellent
    information in support of readers.

  27. Auto Accident Lawyer For Hire: What’s No One Is Talking About car crash attorney Near me

  28. LarryCoell表示:

    slot oyunlar? puf noktalar? slot tr online slot oyunlar?

  29. Diplomi_fper表示:

    купить диплом об окончании 11 классов prema365-diploms.ru .

發佈留言

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