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,665,155 Responses

  1. Montebeera表示:

    canadian pharmacy drugs online online canadian pharmacy no prescription is canadian pharmacy legit

  2. JamesGag表示:

    canadian online pharmacy: canada pharmacy no prescription – recommended canadian pharmacies

  3. Montebeera表示:

    reliable mexican pharmacies Mexican Pharm International mexican pharmacy online order

  4. Arthurhow表示:

    http://indiamedfast.com/# online medicine shopping in india
    canadian pharmacy drugs online

  5. RobertFab表示:

    Starda Casino is a modern online gaming portal offering an exciting world of gambling entertainment. Anyone looking for quality slots, card games and sports betting will find everything they need for entertainment and, perhaps, winning Казино Starda официальный сайт

  6. Тут можно преобрести навес для двух машин в Санкт-Петербурге подробно на сайте навес из поликарбоната

  7. mostbet_rkma表示:

    мостбет мобильная версия скачать мостбет мобильная версия скачать .

  8. Georgewhend表示:

    cheapest online pharmacy india: IndiaMedFast.com – India Med Fast

  9. URL - zyk表示:

    Experience the thrill of playing at 4rabet with quick login through the 4rabet platform. Whether you love 4 ra bet sports betting or casino games , our platform brings it all on one site . Get the 4rabet mobile app for instant and seamless gaming to your favorite games . Explore the 4rabet main site today and explore the world of 4ra bet excitement . Register now and take your gaming experience to the next level !

    Enjoy the thrill of online gaming with 4rabet, your best destination for sports betting and online gambling in India. Whether you follow football or a variety of games, the 4rabet official website provides a easy-to-use interface to place your bets and earn rewards . With the 4rabet application, you can enter your player dashboard anytime , anywhere , guaranteeing you never miss out . The 4ra bet platform is designed for both new players and high rollers, offering a vast collection of gambling choices and live dealer experiences.

    Join the 4rabet online community now and enjoy a reliable, intuitive betting system. Whether you like using 4rabet on your computer or tablet, the online casino fun is unmatched . Begin playing with the 4rabet platform and elevate your casino fun to the ultimate thrill!

    Link: https://edcentral.uk/edblog/beginner-guides/a-beginners-guide-to-professor-doug-lemov-1

    The 4rabet platform offers a effortless experience for casino enthusiasts and casino fans in India. With the 4rabet login process being quick and encrypted, users can access their profiles effortlessly . The smartphone access guarantees accessibility for those on the go , allowing them to enjoy their favorite games . The 4rabet website provides a extensive list of sports events, including basketball, and many other games , tailored specifically for Indian players . The betting hub is beginner-friendly, ensuring smooth access for both new users and high-stakes users to enjoy. By checking out the official gaming page, members can claim high-value bonuses . The 4rabet casino is famous for its strong reputation and fast payouts , providing a trustworthy online gambling journey. Whether you prefer sports betting or live dealer experiences, our platform has something for everyone .

  10. Link - Elani表示:

    Internet-based gambling hubs have transformed the gambling scene, delivering a unique kind of user-friendliness and diversity that traditional establishments can’t match. Recently, a growing community around the world have embraced the fun of digital casino play thanks to its accessibility, engaging traits, and progressively larger range of offerings.

    If you’re exploring for the first time with the world of virtual gambling or hope to delve deeper into trusted platforms, why not sign up for our lively community? It’s a place where gamblers exchange tips, helping you to get the most out of your online casino experience. Explore the experience and see it here now:

    One of the key draws of virtual gambling hubs is the vast selection of gaming experiences available. Whether you love playing on traditional one-armed bandits, diving into narrative-rich thematic slots, or strategizing in classic casino games like Texas Hold’em, internet-based gambling sites deliver infinite choices. Several sites also present live dealer games, making it possible for you to communicate with real dealers and fellow gamblers, all while enjoying the immersive feel of a land-based casino from anywhere you want.

    Apart from the game range, internet-based gambling hubs excel ease of access.

  11. Arthurhow表示:

    http://interpharmonline.com/# canadian valley pharmacy
    canada drugs reviews

  12. Ronnielot表示:

    Came across an interesting article highly recommend you check it out https://telegra.ph/The-best-online-casinos-of-2025-03-22

  13. Georgewhend表示:

    cheapest pharmacy canada: Cheapest online pharmacy – canadian pharmacies comparison

  14. When someone writes an piece of writing he/she keeps the image of a user in his/her brain that how a user
    can know it. So that’s why this piece of
    writing is perfect. Thanks!

  15. Drug information. Generic Name.
    amoxicillin sensitive to sunlight
    Some news about drugs. Read now.

  16. Excellent post. I used to be checking continuously this
    blog aand I aam impressed! Very hellful information specially thhe remaining section 🙂 I deal with such information a lot.
    I used to be looking for this particular information for a luxury car service long island time.
    Thank you and good luck.

  17. Georgewhend表示:

    reliable mexican pharmacies: mexican pharmacy online order – mexican pharmacy online store

  18. Williszew表示:

    http://mexicanpharminter.com/# mexican pharmacy online store

  19. JamesGag表示:

    India Med Fast: cheapest online pharmacy india – lowest prescription prices online india

  20. En tant que stimulant, le modafinil a le potentiel d’augmenter la vigilance, la concentration et le rendement au travail chez certaines personnes. Il est mГ©tabolisГ© dans le foie par le CYP3A4. Cela est dГ» Г  son interaction avec les transporteurs de dopamine dans les synapses. Le modafinil est disponible sous diffГ©rentes formes posologiques, notamment les comprimГ©s, les comprimГ©s Г  croquer et les comprimГ©s sublinguaux. Le modafinil est un agoniste sГ©lectif de la pompe de recapture de la dopamine ; cette interaction augmente l’activitГ© dopaminergique dans le cerveau et augmente l’Г©veil. Un effet secondaire extrГЄmement rare qui peut survenir est le syndrome de Cushing. Le modafinil est parfois appelГ© une version en vente libre des amphГ©tamines. Comme les systГЁmes de rГ©troaction naturels agissent pour rГ©tablir l’homГ©ostasie, le cerveau est capable de rГ©cupГ©rer et de se restructurer. Le modafinil est structurellement similaire Г  l’amphГ©tamine et Г  la mГ©thamphГ©tamine. Les Г©tudes ont gГ©nГ©ralement utilisГ© des doses de 200 mg et 400 mg. C’est un stimulant non amphГ©tamine qui est un antagoniste sГ©lectif des rГ©cepteurs О±1-adrГ©nergiques, un agent libГ©rant de la sГ©rotonine et un agoniste du rГ©cepteur de l’histamine-1. https://nootropiquepharmacie.com/acheter-modafinil-100-mg-pas-cher/ Le modafinil a Г©galement Г©tГ© Г©tudiГ© chez les personnes atteintes de troubles cognitifs et de dГ©mence. Le modafinil est utilisГ© pour traiter la somnolence excessive qui survient chez les patients atteints de narcolepsie, une affection neurologique qui perturbe le rythme du sommeil et provoque la somnolence. Il est Г©galement utilisГ© dans le traitement de la somnolence diurne excessive associГ©e Г  la consommation excessive d’alcool et d’autres stimulants, tels que les amphГ©tamines. Les effets secondaires du modafinil sont trГЁs similaires Г  ceux d’autres stimulants du systГЁme nerveux. Le modafinil doit ГЄtre pris avec un verre d’eau. Jusqu’Г  80 % du modafinil inhalГ© peut ГЄtre exhalГ© par les poumons. Trouble du sommeil liГ© au travail postГ© : en raison de sa capacitГ© Г  rГ©veiller le cerveau, le modafinil peut ГЄtre utilisГ© pour le traitement du trouble du sommeil liГ© au travail postГ©. Comme avec tous les mГ©dicaments, cependant, une rГ©ponse Г  la dose spГ©cifique utilisГ©e n’est pas garantie. Le brevet appartient Г  la sociГ©tГ© franГ§aise ELF Science, qui poursuit actuellement plusieurs versions gГ©nГ©riques. La toxicitГ© est peu probable dans la plupart des cas, mais peut survenir lorsqu’une personne prend trop de mГ©dicament, a des problГЁmes rГ©naux ou hГ©patiques ou y est allergique.

  21. mostbet_pgma表示:

    поддержка мостбет поддержка мостбет .

  22. pdacenter.ru – сервис по ремонту бытовой техники
    Ремонт квадрокоптеров в Перми в официальном сервисном центре PDACENTER.
    Наши инженеры выполняют ремонт любой сложности по дотупным ценам!

  23. pdacenter.ru – сервис по ремонту бытовой техники
    Ремонт стиральных машин в Уфе в официальном сервисном центре PDACENTER.
    Наши инженеры выполняют ремонт любой сложности по дотупным ценам!

  24. TolikIncap表示:

    dark web market urls https://github.com/abacuslink4jjku/abacuslink – darknet marketplace

  25. Arthurhow表示:

    https://interpharmonline.shop/# canadian discount pharmacy
    canadian pharmacy cheap

  26. Williszew表示:

    https://mexicanpharminter.shop/# buying from online mexican pharmacy

發佈留言

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