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,370,409 Responses

  1. HaroldBig表示:

    rybelsus pill: rybelsus price – rybelsus coupon

  2. hergvpodm表示:

    The UEFA EURO 2024 starts on Friday, 14 June, with the match between Germany and Scotland in Munich and ends on 14 July with the final in Berlin. In the first match in Berlin, on 15 June, Spain and Croatia will face each other. UEFA EURO 2024 will conclude with the final match on 14 July in Olympiastadion Berlin. We’ve put together some of the best open-air beer gardens and terraces where you can watch Euro 2024 matches, so you can enjoy the best of the summer sun and sport. All venues serve food and drink (both alcoholic and non-alcoholic). In June and July 2024, the Olympiastadion Berlin will once again be transformed into a temple of football: As the largest of all 10 stadiums in the UEFA EURO 2024, six games will take place in the Olympiastadion Berlin. Highlight: The final on July 14th, 2024.
    https://moviebreak.de/users/platsupafah1980/edit
    On our football live scores pages that covered yesterday’s soccer matches, you will find a comprehensive and statistically packed summary of each match.So if you didn’t see the live soccer scores, you can find out what happened now. In an instant, by simply scrolling down the screen you will discover the scores of each of yesterday’s matches, competition by competition. What were the scores yesterday in the Premier League? In Ligue 1? In the French Cup or in the Champions League? In one glance, you have access to all the data that interests you. And that’s not all, as you can read in the following paragraph. สำหรับผลบอลภาษาไทยกรุณาคลิ๊กเลือกหน้าที่ต้องการ ด้านล่างนี้ได้เลยครับ

  3. A Time-Travelling Journey What People Said About Three Wheeler Pushchair 20
    Years Ago 3 wheel pushchair

  4. pmsmxwceq表示:

    His 17 assists in all competitions also make him Chelsea’s most creative player this season with Palmer alone playing a part in 47.5 per cent of the club’s Premier League goals this season. Cole Palmer’s third goal, in the 111th minute of the match, was the latest a winner has been scored in Premier League history. With just 39 points from 27 games, Chelsea languish in the bottom half and are nearly as close to the relegation zone as the Champions League places. Looking at the underlying numbers, though, the Blues rank fourth in the division for expected goal difference per game (0.36) when in reality it's 0.07. Match Logs (Premier League) Jake Mintz & Jordan Shusterman talk about Joey Votto deciding to retire, the Mariners firing Scott Servais after nine years, the Angels extending Perry Minasian and give their picks for The Good, The Bad and The Uggla for this week.
    https://base-directory.com/listings12832839/tomorrow-ipl-match-date
    Semi-finals Spain and England will contest the final of Euro 2024 on Sunday (July 14), kicking off at 20:00 BST 21:00 CEST at the Olympiastadion in Berlin, Germany. Italy got their hands on the coveted European Championship trophy for a second time. The final of the 2020 tournament was held at Wembley Stadium in London on July 11, 2021, where the Azzurri defeated the Three Lions in a dramatic penalty shootout after the match ended 1-1 following extra time. “They were in a final, they were in the last final of the Euros, of course, and that was at Wembley, and that ended up in huge disappointment . SOCIAL MEDIA UEFA Euro Cup Winners List (1960-2016) It's a question a lot of people will be asking during the Euro 2020 final at Wembley “Here we are, champions of Europe,” said Nico Williams, whose opening goal for Spain in the 47th minute was canceled out by England substitute Cole Palmer in the 73rd. “We are thrilled and hope this can keep going and we can go for the (2026) World Cup.”

  5. Thanks a bunch for sharing this with all of us you really know
    what you are speaking approximately! Bookmarked.
    Kindly additionally seek advice from my site =). We may
    have a link change contract among us!

  6. BarryDof表示:

    https://rybelsus.shop/# rybelsus pill

  7. Kudos, Valuable information!

  8. BarryDof表示:

    http://rybelsus.shop/# rybelsus cost

  9. Профессиональный сервисный центр по ремонту планшетов в Москве.
    Мы предлагаем: ремонт стекла планшета
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  10. This Story Behind Mobility Scooters Will Haunt You Forever!
    foldable Lightweight scooters

  11. Roma表示:

    15 Best Pinterest Boards Of All Time About Fireplace Wall Mount wall fire place; Roma,

  12. BarryDof表示:

    http://rybelsus.shop/# rybelsus pill

  13. 15 Gifts For The Peugeot 308 Key Fob Replacement Lover In Your
    Life car key cover peugeot

  14. HaroldBig表示:

    semaglutide tablets: rybelsus price – semaglutide online

  15. Frankevild表示:

    https://ozempic.art/# ozempic online

  16. BarryDof表示:

    https://ozempic.art/# Ozempic without insurance

  17. kkigvifdb表示:

    Listen to the latest Football Daily podcast We are working hard to get it back online. “His future is at Manchester United, no doubt.” Brentford stand firm on Toney fee – Wednesday’s gossip Don’t miss a move! Sign up for a FREE NewsNow account and get our daily email alert of the top transfer stories. Listen to the latest Football Daily podcast Joshua Zirkzee announced himself at Manchester United by scoring a late winner on his debut to secure an unconvincing 1-0 win over Fulham for Erik ten Hag’s side. He has managed to keep eight clean sheets already this season and his performances could see him land a spot in England’s Euro 2020 squad. What do fans really think about the new campaign? We travelled to games at Manchester United, Arsenal, Chelsea and Leicester to find out Your complete guide to the latest Man Utd transfer news for the 2024 summer window.
    https://jaidenolfa627394.wizzardsblog.com/29880217/sports-cricket-live-score
    With the expanded format in the knockout stage, 16 teams will battle it out in single-elimination matches, culminating in the grand finale at Berlin’s Olympiastadion. They had been lambasted by their media and fans for a poor defensive display in their final group game, a 3-2 loss to Austria, but were more composed and in control as they reach the Euro quarter-finals for the first time since 2008. 16 07 2024 at 16:02 European football history will be written in Berlin in 2024. Be there when 2.5 million football fans from 120 countries cheer on their team in Berlin as they compete for the trophy. In addition to six UEFA EURO 2024 matches in Olympiastadion Berlin, you can expect an exciting cultural and supporting programme and, of course, the biggest Fan Zone in the world! As for the Belgians, they head home after a fairly miserable Euro 2024, during which the players were jeered loudly by their own fans following a 0-0 draw with Ukraine at the end of the group stage.

  18. BarryDof表示:

    https://ozempic.art/# ozempic online

  19. 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://aliensvspredator.org/wiki/index.php?title=1x-slots-brasil.com_18h”

  20. Brigette表示:

    Electric Fireplace Wall Mounted: What’s No One Has
    Discussed wall fires (Brigette)

  21. Highly descriptive post, I loved that a lot. Will
    there be a part 2?

  22. 15 Gifts For The Replacement Windows Bedford Lover In Your Life
    Front Doors Bedfordshire

  23. Профессиональный сервисный центр по ремонту автомагнитол в Москве.
    Мы предлагаем: ремонт автомагнитолы
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  24. perfect表示:

    I am curious to find out what blog system you happen to be using?

    I’m experiencing some minor security problems with my latest blog and I would like to find something more risk-free.
    Do you have any recommendations?

  25. Профессиональный сервисный центр по ремонту автомагнитол в Москве.
    Мы предлагаем: починить магнитолу
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  26. 9 . What Your Parents Taught You About Vauxhall Insignia Key Replacement vauxhall insignia key

  27. Leon表示:

    Five Killer Quora Answers On Standing Desk Treadmill standing desk treadmill (Leon)

  28. Regards. I like this!

發佈留言

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