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,448,763 Responses

  1. Dannyfut表示:

    dark market link deep web drug url https://github.com/darknetmarkets24/darknet-markets – dark web search engines

  2. Dannyfut表示:

    deep web drug markets darknet drug store https://github.com/darknetmarkets24/darknet-markets – deep web search

  3. AngelCroft表示:

    ug5r.ru — Индивидуальные решения для вашего дома.

  4. вывод из запоя в стационаре воронежа https://www.vyvod-iz-zapoya-v-stacionare-voronezh24.ru .

  5. Dannyfut表示:

    deep web search blackweb official website https://github.com/darknetmarkets24/darknet-markets – deep dark web

  6. Feel free to visit my blog; Daycare Near Me

  7. What’s The Current Job Market For ADHD Tests For Adults Professionals?
    online Test For adhd

  8. See What Sliding Patio Door Repair Tricks The Celebs Are Making Use Of Patio Door repair

  9. See What ADHD Medication Names Tricks The Celebs Are Using
    adhd Medication names

  10. Aaron表示:

    The 10 Scariest Things About Patio Door Repair Company patio door repair company (Aaron)

  11. MichaelJup表示:

    FTP Software Lab is a premier informational resource dedicated to the FTP protocol, its ftp commands, ftp clients, ftp related technologies, and current news. We provide a comprehensive guide to understanding and utilizing FTP for secure and dependable file transfers, exploring the various aspects of this essential protocol. FTP lab features detailed insights into a range of FTP client software options, helping you choose the best tools to manage your ftp file transfers efficiently, from effortlessly ftp uploading data to reliably ftp downloading files from ftp servers. Discover the capabilities of intuitive ftp features such as drag-and-drop functionality, and how robust directory ftp synchronization ensures that your local and remote files are consistent. We delve into the technical aspects, explaining secure transfer protocols like SFTP and FTPS, which provide crucial data protection during ftp transmission. Stay up-to-date with the latest innovations in FTP technologies and gain a deeper understanding of this essential ftp protocol through our constantly updated content. We are also committed to keeping you informed about the most relevant news and trends impacting the FTP landscape.

    https://ftplab.com/ – ftp client free

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

  13. CurtisBam表示:

    mexico pharmacies prescription drugs: Mexican Easy Pharm – Mexican Easy Pharm

  14. Dannyfut表示:

    tor marketplace deep web links https://github.com/darknetmarkets24/darknet-markets – deep web drug store

  15. ScottDeall表示:

    Форум предназначен для обсуждения вопросов, связанных с видеонаблюдением и безопасностью. Участники могут делиться информацией и опытом в области программного обеспечения для видеонаблюдения на ПК, совместимого с IP-камерами. Рассматриваются комплексные решения, VMS, CMS, а также технологии AHD и IP. Обсуждаются вопросы настройки, восстановления паролей камер, и применения ИИ-видеоаналитики. Отдельное внимание уделено применению интегрированной видеоаналитики на основе искусственного интеллекта, включая обнаружение объектов, распознавание автомобильных номеров и лиц, а также выявление признаков дыма и огня. Форум является площадкой для обмена знаниями и обсуждения актуальных тем в области видеонаблюдения. Здесь пользователи могут делиться своим опытом, задавать вопросы и находить решения для своих задач. Форум служит платформой для обмена знаниями и поиска решений в сфере видеонаблюдения.
    https://securityvideo.ru/ – vms программа для видеонаблюдения

  16. для вывода из запоя в стационаре http://www.vyvod-iz-zapoya-v-stacionare21.ru/ .

  17. 10 Inspirational Graphics About ADHD Diagnosis UK Private private adhd assessments

  18. вывода из запоя в стационаре vyvod-iz-zapoya-v-stacionare21.ru .

  19. How Do I Explain How To Program A Volkswagen Key To A Five-Year-Old volkswagen key fob

  20. Brandonnot表示:

    IndianCertPharm: IndianCertPharm – Indian Cert Pharm

  21. Antoniofep表示:

    Bet Zula, en populer bahis platformu konusunda yenilikci cozumler sunar. buyuk futbol kars?lasmalar? icin Betzula giris yaparak yuksek oranlar? kesfedebilirsiniz.

    Betzula’n?n mobil uyumlu tasar?m?, profesyonel hizmet garantisi verir. Bet Zula sosyal medya hesaplar?yla yeni kampanyalardan haberdar olabilirsiniz.

    Fenerbahce ve Galatasaray gibi buyuk tak?mlar?n heyecan?n? Betzula ile yasayabilirsiniz.

    Ayr?ca, bet zula giris linki, kullan?c?lara s?n?rs?z erisim sunar. Ozel olarak, https://apsistek.com/yeni-giris/ – betzula guncel giris, profesyonel bir deneyim saglar.

    Betzula, spor bahislerinden canl? casino oyunlar?na kadar tum kullan?c?lar?n ihtiyaclar?n? kars?lar. Fenerbahce Galatasaray derbisi icin bahis yapmak icin Betzula ile kazanmaya baslay?n!
    707707+

  22. Heya i’m for the first time here. I found
    this board and I find It truly useful & it helped me out much.
    I hope to give something back and aid others like you
    helped me. http://Gomezromeo.ar/index.php?option=com_k2&view=item&id=5

  23. Attractive part of content. I just stumbled upon your web site and
    in accession capital to say that I get in fact
    loved account your blog posts. Any way I’ll be subscribing on your augment and even I success you get admission to persistently rapidly.

  24. CurtisBam表示:

    Mexican Easy Pharm: Mexican Easy Pharm – Mexican Easy Pharm

發佈留言

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