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,141,990 Responses

  1. That is very fascinating, You’re an excessively professional blogger.
    I’ve joined your feed and stay up for searching for more of your
    great post. Also, I’ve shared your web site in my social networks

  2. Aliás, as dicas de apostas esportivas desse tipo podem ser nos mais variados mercados.

    Aliás, é interessante até mesmo equilibrar e fazer alguns palpites seguindo as dicas
    de apostas triplas, outros com as duplas e alguns por conta
    própria. Basta criar sua conta e selecionar a oferta ao fazer o primeiro depósito.
    Após o registro, é crucial verificar sua conta para garantir a elegibilidade de saques futuros.

    Após muita pesquisa e análise de milhares de torneios mundo afora,
    esses prognósticos são levantados. Entretanto, com a análise certa e uma
    boa dose de experiência, essas dicas de apostas esportivas são capazes de guiar os jogadores para bons resultados.
    Afinal, seus palpites devem seguir métodos e estratégias baseados na repetição, análise e
    leitura dos dados, não em momentos aleatórios.
    Dessa forma, muitos apostadores acabam ficando no vermelho por não conseguirem lidar com momentos de grande baixa
    ou vitórias inesperadas. Assim, muitos jogadores ficam com medo do risco ser alto demais e acabam deixando passar boas oportunidades.
    Seus bônus de apostas atraem muitos jogadores.
    Os minutos premiados no Fortune Tiger representam uma adição emocionante ao jogo, proporcionando
    aos jogadores oportunidades adicionais de ganhar recompensas emocionantes e bônus especiais.

    Entre os métodos, está o envio de correspondentes aos estádios, que
    acompanham as partidas ao vivo e fornecem informações detalhadas
    sobre o andamento do jogo, além da coleta de
    dados e consultas em sites confiáveis de estatísticas esportivas.

  3. The 10 Most Terrifying Things About Truck Accident Law Firm truck accident law firm

  4. vimeo.com表示:

    10 Places To Find London Online Clothing Shopping Sites Spotting Scope
    With Tripod – vimeo.com,

  5. Emma表示:

    Good Online Shopping Sites Uk It’s Not As Hard As
    You Think Coleman 765581-Ssi Airbed – Emma

  6. Take A Look At Your Fellow Slot Software Enthusiasts.
    Steve Jobs Of The Slot Software Industry Fruit slots – wzgroupup.Hkhz76.badudns.cc,

  7. I believe everything published made a great deal of sense.
    However, what about this? what if you added a little information?
    I am not suggesting your information is not good., but what if you added something that
    grabbed a person’s attention? I mean JS 依照元素出現數量排序 –
    馬老師 雲端研究室 is kinda boring. You ought to look at
    Yahoo’s home page and watch how they create news titles to grab viewers to click.

    You might add a video or a picture or two to grab people interested about what
    you’ve got to say. In my opinion, it could make your blog
    a little bit more interesting.

  8. Five Killer Quora Answers To Free Casino Slots free casino Slots

  9. 15 Surprising Facts About Slot Demo Gatot Kaca Puri slot Gates of gatotkaca demo (Shinhwaspodium.com)

  10. What’s The Job Market For Double Glazed Window Repairs Professionals?
    double glazed window Repairs

  11. This Story Behind Window Repair Near Is
    One That Will Haunt You Forever! Window Repairs

  12. 15 Up-And-Coming Online Clothes Shopping Near Me Bloggers You Need To See shopping online uk Websites

  13. Hey! Do you use Twitter? I’d like to follow you if that
    would be ok. I’m absolutely enjoying your blog and look forward to new posts.

  14. The No. 1 Question Everyone Working In Car Accident Claim Needs
    To Know How To Answer car accident law firms

  15. When I originally commented I clicked the “Notify me when new comments are added”
    checkbox and now each time a comment is added I get four e-mails with the same comment.
    Is there any way you can remove me from that service?
    Many thanks!

  16. Hollis表示:

    Five Killer Quora Answers To Veterans Disability Legal veterans disability, Hollis,

  17. What i do not realize is in truth how you are not really
    a lot more well-liked than you might be right now. You are
    very intelligent. You realize thus considerably with regards
    to this topic, produced me in my opinion consider it from numerous varied angles.

    Its like men and women are not interested until it’s one thing
    to accomplish with Woman gaga! Your personal
    stuffs excellent. At all times deal with it up!

  18. Joy表示:

    The Ultimate Glossary For Terms Related To Jaguar Keys
    Replacement 2003 jaguar x type key replacement (Joy)

  19. See What Double Glazing Units Near Me Tricks The Celebs Are Using double glazing units near me

  20. The number of waffle tokens forms 1,000,000,000 waffles. https://wafflestoken.com/ on the ethereum blockchain.

  21. Online Shopping Sites Uk Tips That Will Transform Your
    Life The Last Of Us Gameplay

  22. Vimeo.com表示:

    The Next Big Trend In The Shopping Online Uk Industry
    Vimeo.com

  23. 네이버 아이디 판매
    저희는 네이버 아이디 판매 전문 업체입니다.
    우리는 귀사의 요구를 총족시키기 위해 최선을 다하고 있습니다.

  24. Artrecord.kr表示:

    10 Things We All We Hate About Injury Attorneys Injuries (Artrecord.kr)

  25. The 10 Worst Double Glazed Windows Near Me Failures Of All Time Could Have Been Prevented double Glaxing

  26. Veronique表示:

    15 Up-And-Coming Bentley Key Price Bloggers You Need To See bentley
    leather key case, Veronique,

  27. Magnificenmt goods fгom you, man. I have understand yoir stuff previous to
    andd y᧐u’re just extremely wonderful. I really like
    what you have acquired here, really like what you’re
    stating and the way in which you say it. You make iit
    entertaining and you still care for to қeep it sensible.
    I cant wait to read much more frim you. This is actually a great Historical site news.

  28. The Best Way To Explain Best Online Shopping Websites Uk To Your Boss Bicycle Lights Front And Rear

  29. Do yⲟu mind if I quote a couple of your articles
    ɑs long ass I provide creditt аnd sources ƅack tto yoսr
    blog? Mү blog is inn tһe exact sаme niche as yours and my users wоuld rewlly benefit from a lot off thee іnformation yօu рresent herе.
    Pleasse let me кnow if this ok witһ you.
    Thanks!

    Check ߋut my web-site; Áo khoác da nữ xịn Hàn Quốc

  30. Ten Things You Shouldn’t Share On Twitter sugar rush big win

發佈留言

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