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,366,765 Responses

  1. Tesofensine’s influence on natural chemicals can cause central
    nervous system adverse effects.

  2. Hey There. I found your weblog the usage of msn. This is a really smartly written article.
    I will make sure to bookmark it and come back to learn more
    of your helpful info. Thank you for the post. I will certainly
    return.

  3. What’s The Most Creative Thing Happening With Auto Locksmith
    Near Me Prices Auto key smith

  4. togel4d login表示:

    9 . What Your Parents Taught You About Togel4d Login togel4d login

  5. Jeremypag表示:

    cheapest rybelsus pills buy semaglutide online rybelsus price

  6. RamonRek表示:

    rybelsus cost: buy semaglutide pills – buy rybelsus online

  7. marketing表示:

    It’s an awesome paragraph in favor of all
    the online visitors; they will obtain benefit from it I
    am sure.

  8. Excellent beat ! I would like to apprentice while
    you amend your site, how could i subscribe for a blog site?

    The account aided me a acceptable deal. I had been a
    little bit acquainted of this your broadcast provided bright clear concept

  9. Diego表示:

    Hi, I do believe this is an excellent site. I stumbledupon it 😉 I’m going to return once again since i have saved as a favorite it.
    Money and freedom is the greatest way to change, may you
    be rich and continue to guide others.

  10. Jeremypag表示:

    semaglutide cost buy rybelsus online buy rybelsus online

  11. It’s a pity you don’t have a donate button!
    I’d definitely donate to this outstanding blog!
    I suppose for now i’ll settle for book-marking and
    adding your RSS feed to my Google account. I look
    forward to brand new updates and will share this site with my
    Facebook group. Talk soon!

  12. O site **1x Slots Brasil** oferece uma experiência de
    jogo online única, com uma vasta gama de slots, jogos de mesa e promoções
    exclusivas. Se você está à procura de diversão e a oportunidade de ganhar grandes prêmios, 1x Slots
    é a plataforma ideal para você.

    ### Vantagens de jogar na 1x Slots Brasil

    1. **Variedade de jogos**: O site apresenta uma extensa
    coleção de jogos de slots de diferentes temas, incluindo
    jogos clássicos de frutas, slots de vídeo, e
    slots com jackpots progressivos. Além disso, você
    pode desfrutar de jogos de mesa como roleta, blackjack e pôquer.

    2. **Bônus e promoções**: Na 1x Slots, os novos jogadores recebem generosos
    bônus de boas-vindas, e os jogadores recorrentes podem aproveitar
    promoções regulares, cashback e rodadas grátis.

    O sistema de recompensas permite acumular pontos e trocar por prêmios exclusivos.

    3. **Interface amigável**: O site é projetado para oferecer uma navegação fácil e intuitiva, permitindo que os jogadores encontrem rapidamente
    seus jogos favoritos e acessem promoções sem complicações.

    4. **Segurança e confiabilidade**: A 1x Slots
    Brasil utiliza as mais avançadas tecnologias de segurança para garantir que
    suas informações pessoais e financeiras estejam sempre protegidas.
    Todos os jogos são auditados para garantir justiça e transparência.

    ### Como começar

    É muito simples começar a jogar no **1x Slots Brasil**.
    Basta fazer um cadastro rápido no site, escolher seu método de pagamento preferido e fazer seu primeiro depósito.
    Você estará pronto para mergulhar no mundo emocionante dos jogos de
    cassino, aproveitando todas as oportunidades de diversão e ganhos.

    ### Suporte ao cliente

    Se surgir qualquer dúvida, a equipe de suporte está sempre pronta
    para ajudar, disponível 24/7 por meio de chat ao vivo ou e-mail.
    O objetivo da **1x Slots** é garantir que você tenha uma experiência de jogo tranquila
    e prazerosa.

    Explore agora a incrível seleção de jogos e promoções em **1x
    Slots Brasil** e descubra por que tantos jogadores escolhem nossa plataforma para diversão e
    grandes chances de ganhar. Não perca a oportunidade de participar deste mundo de entretenimento e recompensas!

    “https://wolvesbaneuo.com/wiki/index.php/User:RSUSusannah”

  13. This History Behind Bandar Toto Can Haunt You Forever!
    Togel singapore

  14. Appreciate this post. Let me try it out.

  15. First of all I want to say wonderful blog! I had a quick question that I’d like to
    ask if you do not mind. I was curious to find out how you center yourself and clear
    your mind prior to writing. I have had a hard time clearing my thoughts in getting
    my thoughts out there. I do enjoy writing but it just seems like the
    first 10 to 15 minutes are usually wasted just trying
    to figure out how to begin. Any suggestions or tips?

    Kudos!

  16. Hi, Neat post. There is a problem along with your web site
    in internet explorer, would check this? IE nonetheless is the market leader and a
    large component of other people will pass over your fantastic writing because of this problem.

  17. You’ll Never Guess This Can Tilt And Turn Windows Open Outwards’s Tricks can tilt and turn Windows open outwards

  18. HaroldBig表示:

    semaglutide online: buy semaglutide pills – rybelsus cost

  19. HaroldBig表示:

    ozempic online: buy ozempic – Ozempic without insurance

  20. Retro Fridge Freezer Uk Tools To Ease Your Daily Life Retro Fridge Freezer
    Uk Trick That Every Person Should Learn retro Fridge freezer Uk

  21. NathanHip表示:

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

  22. Ward表示:

    We’ve Had Enough! 15 Things About Treadmill Folding Incline We’re Sick Of Hearing are all
    treadmill inclines the same – Ward,

  23. BTC Alora表示:

    This excellent website truly has all the information I wanted concerning this subject and didn’t know who to ask.

  24. BarryDof表示:

    https://rybelsus.shop/# semaglutide cost

  25. Are You Getting The Most The Use Of Your Mobility Scooter Buying Guide?
    premium mobility scooters

  26. What Is Under Desk Treadmill With Incline And Why
    Is Everyone Talking About It? Health And Fitness

  27. Hi my loved one! I wish to say that this article is awesome, great written and come with approximately all important infos.
    I would like to look extra posts like this .

    my web site: Mostbet Casino India

  28. BarryDof表示:

    https://rybelsus.shop/# rybelsus cost

  29. **1win Togo: Votre Destination de Paris en Ligne Fiable et
    Innovante**

    Bienvenue sur **1win Togo**, votre plateforme de paris en ligne de confiance,
    où l’innovation rencontre la simplicité pour vous offrir la meilleure
    expérience de jeu possible. Que vous soyez
    un amateur de paris sportifs, un passionné de casino ou un joueur occasionnel cherchant du
    divertissement, 1win Togo vous propose une large gamme d’options pour satisfaire toutes vos envies de jeu.

    ### Une Plateforme de Paris Sportifs Diversifiée

    Chez 1win Togo, nous comprenons l’importance de la diversité pour les parieurs sportifs.
    C’est pourquoi nous couvrons un large éventail de sports : football, basketball,
    tennis, rugby, et bien d’autres. Vous pouvez parier
    sur vos équipes et événements favoris, que ce
    soit à l’échelle nationale ou internationale.

    – **Des cotes compétitives** : Nous offrons des cotes parmi
    les plus attractives du marché pour maximiser vos gains.

    – **Une interface intuitive** : Notre plateforme est facile à utiliser, que vous soyez
    un parieur expérimenté ou débutant. Placez vos paris rapidement
    et en toute sécurité.

    ### Un Casino En Ligne Exceptionnel

    Si vous préférez l’univers des casinos en ligne, **1win Togo** met à votre disposition une vaste collection de jeux de casino.
    Des machines à sous modernes aux jeux de table classiques comme la roulette, le blackjack et le poker, chaque joueur trouvera quelque chose à son goût.

    – **Machines à sous à jackpot** : Tentez votre chance sur nos machines à sous à
    jackpot progressif et décrochez des gains incroyables.
    – **Jeux en direct** : Pour une expérience plus immersive, profitez de nos jeux en direct avec des croupiers professionnels.

    ### Pourquoi Choisir 1win Togo ?

    1. **Sécurité et fiabilité** : Nous mettons un point d’honneur à assurer la sécurité de
    vos données personnelles et de vos transactions. Nos systèmes sont hautement sécurisés
    pour garantir une expérience de jeu sans
    souci.

    2. **Promotions et bonus attractifs** : Chez **1win Togo**, chaque
    nouveau joueur bénéficie de généreux bonus de bienvenue,
    ainsi que de nombreuses promotions régulières pour nos
    membres existants.

    3. **Support client réactif** : Notre équipe d’assistance est
    disponible 24/7 pour répondre à toutes vos questions
    et vous aider à résoudre vos préoccupations rapidement.

    ### Inscription Facile et Rapide

    Rejoindre **1win Togo** est simple et rapide. En quelques minutes,
    vous pourrez créer votre compte, effectuer votre premier dépôt et commencer à jouer.
    Notre processus d’inscription est conçu pour être fluide afin que vous puissiez profiter
    de l’action sans attendre.

    **Ne perdez plus de temps !** Rejoignez la communauté 1win Togo dès aujourd’hui et découvrez un monde de divertissement, de paris sportifs et de jeux de
    casino, avec des chances de gagner des récompenses excitantes à chaque instant.

    “https://mixup.wiki/index.php/User:AdelaWilber7026”

  30. Jeremypag表示:

    Ozempic without insurance ozempic ozempic cost

發佈留言

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