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,372,184 Responses

  1. What Can A Weekly Replacement Mazda Key Project Can Change Your Life mazda 2 key (https://hyenabowl13.Werite.net/)

  2. seer表示:

    Unquestionably consider that which you said. Your favourite reason seemed to be at the internet
    the simplest thing to take into account of.
    I say to you, I certainly get annoyed at the same time as other people consider worries that they plainly do
    not understand about. You managed to hit the nail upon the
    highest and outlined out the whole thing without having side-effects
    , folks could take a signal. Will likely be again to get more.

    Thank you

  3. BarryDof表示:

    https://ozempic.art/# ozempic generic

  4. Frankevild表示:

    http://rybelsus.shop/# buy rybelsus online

  5. Jeremypag表示:

    semaglutide cost semaglutide tablets semaglutide tablets

  6. Do you mind if I quote a couple of your posts as long as I provide credit and sources
    back to your site? My website is in the exact same area
    of interest as yours and my users would genuinely benefit from some of
    the information you provide here. Please let me know if this okay
    with you. Appreciate it!

  7. HaroldBig表示:

    semaglutide cost: buy semaglutide pills – buy semaglutide online

  8. Frankevild表示:

    https://rybelsus.shop/# semaglutide tablets

  9. torrentfilmi表示:

    I think the admin of this web page is in fact working hard for his web
    site, as here every data is quality based stuff.

  10. Frankevild表示:

    https://ozempic.art/# ozempic online

  11. HaroldBig表示:

    cheapest rybelsus pills: rybelsus price – rybelsus coupon

  12. During the 18th and 19th generations in the best echelons of British society, the English country home was a location for enjoyable, hunting in the countryside. The aristocratic stately dwelling continued the custom of the initially large gracious unfortified mansions such as the Elizabethan Montacute House and Hatfield House. In 2010 and 2011 she acquired the Stirling Prize, the UK’s most prestigious architectural award, and in 2015 she became the 1st woman to be awarded the Royal Gold Medal from the Royal Institute of British Architects. In this era of prosperity and development British architecture embraced quite a few new procedures of building, but these kinds of architects as August Pugin ensured that classic variations ended up retained. Paxton also created this sort of homes as Mentmore Towers, in the continue to common retrospective Renaissance styles. Many of these homes are the setting for British period dramas, these as Downton Abbey. Notable illustrations of Gothic revival architecture are the Houses of Parliament and Fonthill Abbey. A noteworthy style and design is his ArcelorMittal Orbit sculpture at the Olympic Park in London. Other important skyscrapers beneath construction in London incorporate 22 Bishopsgate, and Heron Tower. In German-talking areas, most publications ended up tutorial papers, and most ended up scientific and technological publications, frequently autodidactic practical instruction manuals on matters these types of as dike design.

  13. Frankevild表示:

    https://rybelsus.shop/# semaglutide cost

  14. Roscoe表示:

    Seriously tons of great advice!

  15. Do you have a spam issue on this blog; I also am a blogger, and I was wondering your situation; many of us have created some nice methods and we are looking to swap strategies with other folks,
    why not shoot me an e-mail if interested.

  16. What Freud Can Teach Us About Cheap Triple Bunk Bed double bed and single bed Bunk

  17. NathanHip表示:

    Descubra o horário de brasília e tenha a certeza de estar sempre no fuso horário correto. Perfeito para quem vive ou trabalha na capital e precisa de pontualidade!

  18. olympus188表示:

    Keep on working, great job!

  19. KennethBrode表示:

    просушка помещений после затопления стоимость работы https://sushka-pomeshchenij-v-msk.ru/

  20. RobertVar表示:

    Discovered an intriguing article, I recommend you to check it out Готовим из мяса

  21. RamonRek表示:

    semaglutide tablets: rybelsus coupon – buy semaglutide pills

  22. Frankevild表示:

    https://ozempic.art/# buy ozempic

  23. **1win Côte d’Ivoire** est votre destination incontournable pour profiter pleinement des paris en ligne.

    Que vous soyez passionné de sports ou adepte des jeux
    de casino, 1win vous offre une plateforme moderne et intuitive qui répond à tous vos besoins.

    Avec une large gamme d’options de divertissement et des cotes compétitives, vous pouvez parier
    en toute sécurité tout en profitant de
    bonus généreux.

    ### Pourquoi choisir 1win Côte d’Ivoire?

    1. **Diversité des paris sportifs**
    1win Côte d’Ivoire propose des paris sur une multitude de sports, y compris le football, le basketball, le tennis, et bien plus encore.
    Que vous soyez amateur des compétitions locales ou des grands tournois internationaux, vous trouverez toujours une opportunité de parier sur vos événements préférés avec des cotes attractives.

    2. **Une expérience de casino en ligne exceptionnelle**

    Outre les paris sportifs, 1win offre une vaste sélection de jeux de casino.
    Machines à sous, roulette, blackjack, poker – il y a de quoi satisfaire
    tous les goûts. Tous les jeux sont développés par les meilleurs fournisseurs pour garantir une
    qualité de jeu irréprochable.

    3. **Bonus et promotions attractifs**
    Les nouveaux utilisateurs de 1win bénéficient d’un généreux bonus de bienvenue qui peut multiplier leurs chances de
    gains. De plus, de nombreuses promotions régulières
    sont disponibles pour récompenser la fidélité des joueurs.

    4. **Sécurité et fiabilité**
    La plateforme 1win Côte d’Ivoire est sécurisée et utilise des technologies de cryptage avancées pour
    protéger vos informations personnelles et financières. Vous pouvez parier en toute tranquillité d’esprit.

    ### Comment commencer?

    S’inscrire sur 1win Côte d’Ivoire est simple et rapide.
    Il vous suffit de créer un compte, d’effectuer un dépôt et de commencer à parier ou à jouer à
    vos jeux de casino préférés. L’interface conviviale vous
    permet de naviguer facilement entre les différentes sections, que vous soyez
    sur un ordinateur ou un mobile.

    Ne manquez pas l’opportunité de faire partie de la communauté 1win et de vivre des moments inoubliables en pariant sur vos événements sportifs favoris ou en explorant l’univers passionnant
    du casino en ligne. Inscrivez-vous dès aujourd’hui et commencez
    à gagner avec 1win Côte d’Ivoire!

    “http://kisdiconference.kr/2022/bbs/board.php?bo_table=free&wr_id=3029416”

  24. Spoon Pipes表示:

    When some one searches for his vital thing, therefore
    he/she needs to be available that in detail, thus that thing is maintained over here.

  25. BarryDof表示:

    http://rybelsus.shop/# semaglutide tablets

  26. NathanHip表示:

    Descubra o horário de brasília e tenha a certeza de estar sempre no fuso horário correto. Perfeito para quem vive ou trabalha na capital e precisa de pontualidade!

  27. Jeremypag表示:

    buy semaglutide pills rybelsus coupon cheapest rybelsus pills

  28. BarryDof表示:

    https://ozempic.art/# ozempic online

發佈留言

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