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,125,586 Responses

  1. The provided material of this blog piece is truly fascinating .
    I enjoyed the way you examined the different issues so thoroughly and lucidly .

    You helped me obtain fresh viewpoints that I had not considered
    before. Thank you for sharing your proficiency and skill
    – it has enabled me to acquire knowledge additionally .

    I especially relished the novel perspectives you showcased ,
    which enlarged my mindset and cognition in meaningful paths
    . This blog is organized and compelling , which is critical for material of
    this level .
    I look forward to examine more of your compositions in the times ahead ,
    as I’m convinced it will continue to be informative and
    enable me maintain progressing . I convey
    my thankfulness!

    Also visit my blog post discuss [https://xypid.win/story.php?title=unlock-the-future-of-gambling-explore-the-particular-wonders-of-crypto-casino-bitcoin-online-casino-and-onl]

  2. I’m amazed, I must say. Seldom do I come across a
    blog that’s equally educative and engaging, and without a doubt, you have hit the
    nail on the head. The issue is something which not enough people are speaking
    intelligently about. Now i’m very happy I came across this in my hunt for something regarding this.

    Also visit my blog :: medicine for herpes outbreak

  3. Guide To Birth Injury Lawyer Near Me: The Intermediate Guide Towards Birth Injury Lawyer Near Me Birth injury lawyer Near me

  4. brqwpotvh表示:

    Para mejorar su experiencia, personalizar su uso de YouHodler y analizar nuestro tráfico. Al hacer clic en «Aceptar», consiente el uso de cookies. El AMD Ryzen 3 1200 es un procesador de escritorio con 4 núcleos. Es parte de la línea Ryzen 3 y utiliza la arquitectura Zen (Summit Ridge) con Socket AM4. Ryzen 3 1200 tiene 8 MB de caché L3 y funciona a 3,1 GHz de forma predeterminada, pero puede aumentar hasta 3,4 GHz, según la carga de trabajo. AMD está construyendo el Ryzen 3 1200 en un proceso de producción de 14 nm utilizando 4800 millones de transistores. La virtualización de hardware está disponible en Ryzen 3 1200, lo que mejora enormemente el rendimiento de la máquina virtual. Hashshiny es una empresa de minería en la nube que permite a los usuarios ganar dinero extrayendo bitcoins y otras criptomonedas para ellos. Hashshiny comenzó como un equipo de ex empleados de algunas de las empresas tecnológicas más importantes. Están enfocados en llevar la criptomoneda a las masas y tienen algunas ideas geniales en ese sentido. Casi todos sus centros mineros están en Kazajstán y Myanmar.
    https://tango-wiki.win/index.php?title=Diferencia_entre_tokens_y_criptomonedas
       btc.tv.bo (6 calificaciones Get up to 0.5% cashback per purchase and receive daily interest. El programa AI Seed Phrase Finder es una herramienta poderosa para buscar y validar frases semilla en el mundo de las criptomonedas. Con este programa, los usuarios pueden encontrar frases semilla asociadas a billeteras de Bitcoin y acceder a ellas para recuperar fondos perdidos. El programa ofrece varias versiones con diferentes funcionalidades y niveles de productividad. En este artículo, exploraremos en detalle cómo funciona este programa y cómo puede ayudarte a encontrar y acceder a billeteras de Bitcoin mantenidas abandonadas. en.wikipedia.org wiki Bitcoin Empieza en cripto hoy! Curso gratis Many crypto companies in the past have complained about the lack of clarity surrounding transfers. In the UK, there is more clarity, but the legislation is proving hard to adhere to, and it has put multiple operators out of business.

  5. hijab porn表示:

    I absolutely love your website.. Pleasant colors & theme.
    Did you build this amazing site yourself? Please reply
    back as I’m hoping to create my own personal site and would like to learn where you got
    this from or what the theme is named. Many thanks!

  6. Thank you for the auspicious writeup. It in fact was a amusement account it.

    Look advanced to more added agreeable from you! By the way, how can we communicate?

  7. Thanks for one’s marvelous posting! I seriously enjoyed reading it, you might be a great author.
    I will make certain to bookmark your blog and will
    eventually come back in the foreseeable future.
    I want to encourage continue your great writing, have a nice day!

  8. Dean表示:

    3 Reasons You’re Renault Captur Key Is Broken (And How
    To Repair It) renault captur key card replacement, Dean,

  9. isaevclub.ru表示:

    A Glimpse Into Cost Of Car Key Replacement’s Secrets Of Cost Of Car Key Replacement car key
    Replacement service (isaevclub.ru)

  10. Link Togel表示:

    Link Togel Tools To Ease Your Daily Life Link Togel Trick That Everyone Should Know Link Togel

  11. Easydrorbix表示:

    best rx pharmacy: xenical indian pharmacy – cialis uk online pharmacy

  12. See What Volkswagen Key Programming Tricks The Celebs Are Utilizing volkswagen Key (sciencewiki.science)

  13. Если вы искали где отремонтировать сломаную технику, обратите внимание – профи услуги

  14. Если вы искали где отремонтировать сломаную технику, обратите внимание – ремонт бытовой техники в челябинске

  15. click link表示:

    That is very fascinating, You are an excessively skilled blogger.
    I’ve joined your feed and look forward to looking for extra of your great post.

    Also, I’ve shared your web site in my social networks

  16. Easydrorbix表示:

    lamotrigine pharmacy: buy percocet online pharmacy – bactrim pharmacy

  17. Если вы искали где отремонтировать сломаную технику, обратите внимание – выездной ремонт бытовой техники в челябинске

  18. See What Single Wheel Stroller Tricks The Celebs Are Using Single Wheel Stroller

  19. Если вы искали где отремонтировать сломаную технику, обратите внимание – ремонт техники в челябинске

  20. 9kuan9.com表示:

    14 Companies Doing An Excellent Job At Togel4d Login togel sydney, 9kuan9.com,

  21. shemale fuck表示:

    I visited multiple websites however the audio quality for audio songs present
    at this web page is actually marvelous.

    Also visit my website shemale fuck

  22. mature porn表示:

    Hi there, just became aware of your blog through Google, and found
    that it is truly informative. I’m gonna watch out for brussels.

    I’ll be grateful if you continue this in future. Lots of
    people will be benefited from your writing. Cheers!

    Also visit my blog; mature porn

  23. panfdfzcv表示:

    Una vez resueltas las ecuaciones, las recompensas se comparten con todos los que colaboraron en este proceso. Su principal ventaja es la reducción de los costes individuales de cada minero y el aumento de las posibilidades de resolver el problema matemático lo antes posible. © EXPANSION.COM Avda de San Luis 25 – 28033 MADRID Una web de Unidad Editorial Una vez resueltas las ecuaciones, las recompensas se comparten con todos los que colaboraron en este proceso. Su principal ventaja es la reducción de los costes individuales de cada minero y el aumento de las posibilidades de resolver el problema matemático lo antes posible. Los algoritmos que determinan la dificultad del problema y otras variables hoy día se toman como sistemas de consenso. Esto debido a que se necesita el acuerdo de unas normas por todos los participantes.
    https://wiki.gta-zona.ru/index.php/Cotizacion_luna_crypto
    Ante la ausencia de una licencia en Bitcoin Profit, sospechamos que la web puede estar sujeta a fraudes. Todo lo contrario podemos decir de eToro, que entrega todas las certificaciones de rigor. En el siguiente cuadro comparamos ambos brókeres: Esta forma de fraude a través de la clonación de sitios web ocurrió con MyEtherWallet en 2017. Al año siguiente se clonaron sitios como el popular dominio Blockchain.info y la ICO de Token Bee, en donde los cibercriminales lograron robar hasta 700 mil dólares. Hola, buenas tardes. Sabéis algo de Andrea Redondo en su Club de la Inversión? algunos los acusan de fraudulentos, que derivan a los estudiantes a blokers que trabajan con ellos y nunca se vuelve a recuperar la inversión? alguien podría ayudarme, estoy estudiando con ellos, pero por algún comentario negativo, ya no quisiera continuar. Gracias

  24. Thanks for giving your ideas with this blog. Likewise, a misconception regarding the banking companies intentions any time talking about foreclosed is that the lender will not have my payments. There is a fair bit of time that the bank will take payments here and there. If you are also deep within the hole, they’re going to commonly require that you pay the actual payment in full. However, that doesn’t mean that they will have any sort of payments at all. In case you and the loan company can seem to work a thing out, a foreclosure method may stop. However, if you continue to miss payments under the new system, the foreclosed process can just pick up exactly where it was left off.

  25. Drstobeese表示:

    clomiphene pharmacy: target pharmacy finasteride – femara online pharmacy

  26. The Biggest Problem With Coffee Pods Machine, And How You Can Repair It
    best coffee pod Machine

  27. Drstobeese表示:

    tesco pharmacy orlistat: nexium uk pharmacy – clonidine pharmacy

  28. Howdy! Do you know if they make any plugins to
    help with Search Engine Optimization? I’m trying to get my blog to
    rank for some targeted keywords but I’m not seeing very good success.
    If you know of any please share. Thanks!

  29. 1win app表示:

    An outstanding share! I have just forwarded this onto a colleague
    who had been conducting a little homework on this. And he actually ordered me lunch because I stumbled upon it for
    him… lol. So let me reword this…. Thank YOU for the meal!!

    But yeah, thanks for spending time to talk about this issue here on your web page.

  30. Easydrorbix表示:

    medical mall pharmacy: xl pharmacy sildenafil – Persantine

發佈留言

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