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,126,126 Responses

  1. Excellent website. Plenty of useful info here. I am sending it to a few pals ans additionally sharing in delicious.
    And certainly, thanks to your effort!

  2. Thanks for your personal marvelous posting! I certainly enjoyed reading it, you will be a great author.I will be
    sure to bookmark your blog and will often come back from now on. I want to
    encourage you to continue your great work, have a nice day!

  3. You’ll Never Be Able To Figure Out This Car Ignition Switch Repair’s Tricks car ignition switch repair –
    http://www.valeriarp.com.tr

  4. What Is Mesothelioma Lung Cancer Lawyers? To Use It binghamton mesothelioma lawyer

  5. Hey there just wanted to give you a quick heads up and let you know a few of the images aren’t loading properly. I’m not sure why but I think its a linking issue. I’ve tried it in two different internet browsers and both show the same results.

  6. The Most Significant Issue With Unlock Car Service And How To
    Fix It automotive lock

  7. Easydrorbix表示:

    british pharmacy viagra: rx reliable pharmacy – student store pharmacy hours

  8. See What Coffee Machine For Pods Tricks The Celebs
    Are Utilizing coffee machine for pods

  9. What’s The Current Job Market For Frost Free Retro
    Fridge Freezer Professionals? frost free retro fridge freezer

  10. Drstobeese表示:

    tamoxifen citrate online pharmacy: trusted overseas pharmacies – viagra online uk pharmacy

  11. Easydrorbix表示:

    pharmacy without prescription: Aebgpaype – allopurinol pharmacy

  12. I was curious if you ever thought of changing the page layout of your website?
    Its very well written; I love what youve got to say.
    But maybe you could a little more in the way of content so people could connect with it better.
    Youve got an awful lot of text for only having 1 or two images.
    Maybe you could space it out better?

  13. What’s up friends, its fantastic piece of writing concerning educationand
    entirely explained, keep it up all the time.

  14. This Week’s Top Stories About Electric Running Treadmill Electric Running Treadmill fold away electric treadmill

  15. Greetings from California! I’m bored at work so I decided to browse your website
    on my iphone during lunch break. I enjoy the information you present here and can’t wait to take a look when I get home.
    I’m surprised at how quick your blog loaded on my mobile ..

    I’m not even using WIFI, just 3G .. Anyhow, wonderful blog!

    Check out my webpage: visit our website

  16. Lazrzrr表示:

    Как официально купить диплом вуза с упрощенным обучением в Москве
    fundable.com/originality-diplomik

  17. Easydrorbix表示:

    Female Viagra: indian pharmacy strattera – viagra online pharmacy services

  18. Five Killer Quora Answers To ADHD Private Assessment UK adhd private assessment Uk, maximusbookmarks.com,

  19. clfjawfsk表示:

    Tudo que você precisa é um computador ou celular e acesso a internet para poder buscar ganhos consistentes de R$300, R$600 ou até R$1.780 todos os dias com a sua técnica comprovada de fonte de renda rápida. Depois de descobrir como funcionam os mercados e sentir que está pronto para começar a negociar com dinheiro real, você precisa definir algumas metas. Se você deseja saber como ganhar dinheiro com criptomoedas, esse é um fator muito importante. Se você planeja fazer disso um trabalho de meio período ou período integral, você precisa ter expectativas sobre o quanto espera ganhar. Estudo, leitura e cursos de analistas sérios com experiência são necessários para só depois começar a praticar e operar com um grande “risk management”, ou controle de risco.
    https://www.totalskincarebyliana.com/forum/general-discussions/ethereum-lisbon
    Denise Cinelli, Country Manager da CryptoMarket no Brasil, afirma que os Halvings do bitcoin ocorrem aproximadamente a cada quatro anos, e continuarão até que alcance a oferta máxima de 21 milhões de bitcoins, valor estipulado desde sua criação. A atitude de limitar a oferta é para garantir que não haja inflação. Maior das criptomoedas, o bitcoin voltou a ser negociado abaixo de US$ 29 mil nos negócios da Ásia desta quinta-feira com o mercado de olho em sinais de inflação resiliente, o que deve forçar os bancos centrais a estenderem o aperto financeiro. “Os principais custos de funcionamento dos mineradores de bitcoin é o consumo de energia e, portanto, eles têm um incentivo claro para encontrar e manter fontes baratas, que geralmente são renováveis. As maiores fazendas de mineração de bitcoin geralmente estão localizadas em locais remotos, perto dessas fontes de energia, e aproveitam os baixos custos que seriam impossíveis de transferir para as grandes cidades”, diz Adrian Eidelman, cofundador da RSK, uma plataforma de contrato inteligente e de sidechain de bitcoin.

  20. 9 Lessons Your Parents Teach You About Robotic Vacuum Self Emptying Robotic Vacuum Self Emptying

  21. Why Do So Many People Are Attracted To Car Door Lock Repair Price?
    repair Car lock Doors

  22. usdezlokc表示:

    Muricilândia-TO “The rise in digital assets creates an opportunity to reinforce American leadership in the global financial system and at the technological frontier but also has substantial implications for consumer protection, financial stability, national security, and climate risk. The United States must maintain technological leadership in this rapidly growing space, supporting innovation while mitigating the risks for consumers, businesses, the broader financial system, and the climate. And, it must play a leading role in international engagement and the global governance of digital assets consistent with democratic values and US global competitiveness.” Pesquisador do IBRE FGV, professor do Instituto de Economia … ver mais Fazer uma transferência de criptomoedas é essencialmente o ato de autorizar o movimento de uma quantidade específica de moeda da sua carteira para outra. Esse processo normalmente é verificado por terceiros, conhecidos como mineradores, que acessam sua chave pública para confirmar que sua chave privada foi usada para iniciar a transação. Assim que o bloco que inclui a sua transferência for confirmado, o livro-razão é irreversivelmente atualizado com o novo saldo do seu endereço e do seu destinatário.
    https://source-wiki.win/index.php?title=Omicron_criptomoeda_preço
    O bitcoin (BTC) iniciou a semana oscilando na faixa de US$ 37 mil e próximo da máxima de US$ 37.884 atingida neste ano com os investidores de ativos digitais aguardando para os próximos dias uma aprovação em massa dos fundos negociados em bolsa (ETFs) de criptomoedas à vista. A aposta é que o evento posso acelerar o atual rali das moedas digitais ainda no final do ano, incluindo criptos menores como o ether (ETH), token nativo da rede Ethereum. Os investidores podem estudar padrões na economia mundial para prever a demanda por Bitcoin. Por exemplo, a inflação ocorre frequentemente antes que as bases monetárias das moedas fiduciárias aumentem. Os investidores podem concluir na análise fundamental desse padrão macro que a demanda por Bitcoin como hedge inflacionário aumentará o preço.

  23. Drstobeese表示:

    walgreen pharmacy store locator: online pharmacy cialis reviews – wellbutrin target pharmacy

  24. Sweet blog! I found it while searching on Yahoo News. Do
    you have any tips on how to get listed in Yahoo News?
    I’ve been trying for a while but I never seem to get there!
    Thank you

  25. Easydrorbix表示:

    mexican pharmacy abilify: online pharmacy exelon patch – online pharmacy retin a

  26. I simply couldn’t leave your site before suggesting that I actually enjoyed the usual info an individual supply
    for your guests? Is going to be back steadily to check up on new posts

  27. Asking questions are genuinely fastidious thing if you are not understanding something fully, except this article provides fastidious understanding yet.

    Have a look at my website :: jasa bikin website perusahaan

  28. 10 Things That Your Family Taught You About Keys Locked In Vehicle
    keys locked in vehicle (enfogentraining.com)

  29. The Unspoken Secrets Of Method Titration What Is Titration In Adhd

發佈留言

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