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,626,691 Responses

  1. pikakasinot表示:

    Hello all, the community here is very helpful. Super helpful insights for new people.

  2. JamesGag表示:

    trusted canadian pharmacy: Pharmacies in Canada that ship to the US – canadian pharmacy sarasota

  3. Сияющий порядок и уют в Вашем Доме: Экспертные Услуги Клининговой Компании в Санкт-Петербурге городе на Неве

    Сражены от нескончаемых забот по уборке? Дайте возможность нам попечься о чистоте вашего родного очага или офиса! Наша клининговая компания в Санкт-Петербурге предлагает широкий спектр услуги, которые удовлетворят самые высокие требования к качеству и сервису.

    Доступные цены и понятные условия;
    Высокое качество обслуживания и педантичное деталям;
    Персональный подход к каждому клиенту;
    Точное соблюдение сроки выполнения работ.
    Не ждите, пока грязь и беспорядок станут катастрофой. Дайте нам шанс вернуть вашему пространству чистоту и порядок! Узнайте больше о наших услугах и отправьте заявку на сайте : http://xn--o39at6klwm3tu.com/bbs/board.php?bo_table=free&wr_id=884538

  4. Thank you for the good writeup. It actually was a leisure account it.
    Look advanced to far brought agreeable from you! However, how could we keep up a correspondence?

  5. Williszew表示:

    https://indiamedfast.shop/# online medicine shopping in india

  6. Its like you read my mind! You appear to know a lot about
    this, like you wrote the book in it or something.
    I think that you could do with some pics to drive the message home a little bit, but instead of that, this is wonderful blog.
    A fantastic read. I will definitely be back.

  7. WebSite obliz表示:

    Virtual gambling platforms have changed forever the way people experience casino gaming. Delivering incredible accessibility, they allow players to engage with their most-loved choices anytime, anywhere. With thousands of titles ranging from classic slots to live dealer games and traditional favorites like poker, these venues cater to every style.

    Internet-based gambling hubs have changed the gambling market, offering a unique kind of ease and selection that traditional gambling houses don’t provide. Throughout the last ten years, a large audience globally have turned to the thrill of internet-based gaming due to its ease of access, engaging traits, and progressively larger selection of games.

    If you’re exploring for the first time with the world of virtual casino play or hope to explore trusted platforms, why not engage with our lively social network? It’s a space where fans share stories, making it easier for you to get the most out of your online casino experience. Join the conversation and visit us now: .

    One of the biggest attractions of virtual gambling hubs is the incredible array of choices at your disposal. Whether you are a fan of rolling retro slot machines, exploring story-driven thematic slots, or exercising tactics in classic casino games like Texas Hold’em, virtual venues deliver endless opportunities. Numerous services furthermore offer live casino options, giving you the chance you to engage with live hosts and other players, all while taking in the engaging atmosphere of a land-based casino from anywhere you want.

  8. Georgewhend表示:

    canadian pharmacy online: canadian drugstore online no prescription – canada drugs reviews

  9. My brother suggested I may like this web site. He was entirely right.
    This publish actually made my day. You can not consider
    simply how a lot time I had spent for this info! Thank you!

  10. Link - Elani表示:

    Online casinos have revolutionized the betting scene, providing an exceptional degree of user-friendliness and selection that conventional gambling houses don’t provide. Over time, a growing community across the globe have adopted the thrill of virtual casinos thanks to its accessibility, exciting features, and progressively larger range of offerings.

    If you’re just starting with the world of internet-based gaming or would like to delve deeper into trusted platforms, why not participate in our active gaming forum? It’s a destination where gamblers post experiences, enabling you to improve your online casino experience. Join the connections and learn more now: http://www.mignonmuse.com/bbs/board.php?bo_table=free&wr_id=382556

    One of the most compelling reasons of virtual gambling hubs is the unparalleled variety of titles available. Whether you enjoy playing on vintage reel games, diving into plot-filled modern slot games, or strategizing in traditional table offerings like Blackjack, online platforms boast numerous options. Many casinos furthermore feature live casino options, enabling you to connect with real dealers and fellow gamblers, all while immersing yourself in the authentic feel of a brick-and-mortar establishment in your own space.

    Apart from the game range, virtual gambling platforms are known for seamless entry.

  11. JamesGag表示:

    canadian pharmacy cheap: online canadian pharmacy no prescription – canadian pharmacy cheap

  12. can i get generic furosemide without insurance where can i get furosemide buy furosemide without a prescription
    order furosemide online buying furosemide pill where can i get generic furosemide without prescription
    buying generic furosemide prices
    is furosemide over the counter can i get generic furosemide no prescription cost of generic furosemide without dr prescription
    can i get generic furosemide without a prescription cost generic furosemide no prescription buy furosemide 40mg for sale

  13. Arthurhow表示:

    http://mexicanpharminter.com/# mexican pharmacy online order
    canadian drugs pharmacy

  14. Williszew表示:

    https://interpharmonline.com/# canadapharmacyonline legit

  15. Exactly what I was searching for, appreciate it for putting up.
    비아그라 구매

  16. Arthurhow表示:

    http://interpharmonline.com/# canada pharmacy world
    canadian pharmacy world

  17. Le modafinil est un substrat enzymatique du cytochrome P450 (CYP). Comme tous les mГ©dicaments sur ordonnance, Modafinil doit ГЄtre utilisГ© conformГ©ment aux instructions et avec prudence chez les personnes souffrant de maladies cardiovasculaires, d’hypertension artГ©rielle, d’hypercholestГ©rolГ©mie ou de troubles rГ©naux ou hГ©patiques. Le modafinil n’est pas absorbГ© de maniГЁre systГ©mique lorsqu’il est administrГ© par voie orale, bien qu’il traverse la barriГЁre hГ©mato-encГ©phalique. п»їLe modafinil est un dГ©rivГ© synthГ©tique de la benzhydrylamphГ©tamine. Le constituant chimique actif du modafinil est le R-modafinil, composГ© de deux Г©nantiomГЁres (R-modafinil et S-modafinil). Il se lie Г  la sous-unitГ© alpha des rГ©cepteurs de la dopamine dans le cerveau, entraГ®nant une activitГ© cГ©rГ©brale accrue. Le modafinil est un stimulant du systГЁme nerveux central (SNC) ayant une activitГ© sur les rГ©cepteurs de la dopamine. C’est un stimulant et les mГ©canismes neurohormonaux du cerveau qui stimulent l’Г©veil semblent ГЄtre trГЁs similaires Г  ceux de l’amphГ©tamine et des stimulants apparentГ©s. La clairance totale du mГ©dicament est d’environ les deux tiers de celle de la barriГЁre hГ©mato-encГ©phalique, de sorte que le mГ©dicament ne s’accumule pas dans le corps. N’utilisez pas plus que la dose recommandГ©e de 100 mg et pas plus d’une fois par jour. Le mГ©dicament a Г©tГ© Г©tudiГ© comme traitement de la maladie d’Alzheimer et a Г©tГ© Г©tudiГ© comme traitement des troubles cognitifs, du trouble d’hyperactivitГ© avec dГ©ficit de l’attention (TDAH) et de diverses affections psychiatriques telles que la dГ©pression et l’obГ©sitГ©. La dose maximale utilisГ©e est de 600 mg par jour, bien que la plupart des gens n’aient pas besoin de plus de 200 mg. Le modafinil peut ГЄtre pris quotidiennement, pendant deux semaines maximum. aux Г‰tats-Unis en 1998. La dose recommandГ©e est de 400 mg Г  800 mg le matin, prise sous forme de deux ou trois comprimГ©s de 200 mg, 100 mg ou 50 mg environ 15 minutes avant l’heure prГ©vue d’Г©veil. https://nootropiquepharmacie.com/provigil-france/ Les effets secondaires peuvent inclure des maux de tГЄte, des troubles du sommeil et des nausГ©es, ainsi que des Г©tourdissements, une photosensibilitГ©, des rГЄves vifs, de l’agitation, une augmentation des clignements des yeux et des Г©ruptions cutanГ©es. Le modafinil a Г©tГ© initialement utilisГ© pour traiter la narcolepsie et, plus rГ©cemment, a Г©tГ© utilisГ© hors AMM comme prГ©tendu activateur cognitif pour amГ©liorer l’Г©veil chez les animaux de laboratoire et les humains. Les symptГґmes peuvent inclure un mal de tГЄte, un sentiment d’ГЄtre “espacГ©”, des troubles du sommeil ou un sentiment de paranoГЇa. Le modafinil n’est pas recommandГ© pour une utilisation chez les personnes ayant des antГ©cГ©dents de psychose ou de maladie de Parkinson, ou avec une utilisation chronique de stimulants du SNC tels que la cocaГЇne ou l’amphГ©tamine, ou en raison du risque de problГЁmes cardiovasculaires graves. Le modafinil est disponible en tant que mГ©dicament gГ©nГ©rique ainsi qu’en tant que mГ©dicament de marque coГ»teux. Le composant principal est l’Г©nantiomГЁre modafinil S, le modafinil R est prГ©sent sous sa forme Г©nantiomГЁre R moins active. Le modafinil est dГ©veloppГ© et utilisГ© par Novo Nordisk A/S, une sociГ©tГ© pharmaceutique danoise. Le modafinil n’a pas d’affinitГ© significative pour l’histamine, l’acГ©tylcholine, la sГ©rotonine, les rГ©cepteurs adrГ©nergiques, noradrГ©nergiques, GABA-A, glutamatergiques, cholinergiques ou opioГЇdes. Il y a une grande marge de sГ©curitГ©. Le modafinil peut interfГ©rer avec les canaux potassiques cardiaques et affecter l’action d’autres mГ©dicaments susceptibles d’affecter le cЕ“ur. Il peut Г©galement ГЄtre utilisГ© comme activateur cognitif, bien qu’il ne semble pas amГ©liorer les domaines associГ©s Г  la mГ©moire de travail. Le modafinil stimule la dopamine dans le cerveau en bloquant une enzyme (cocaГЇne et monoamine oxydase de type amphГ©tamine) qui dГ©grade la dopamine. Le fabricant recommande d’utiliser un protocole de titration lente, en commenГ§ant par 100 mg et en augmentant chaque semaine jusqu’Г  ce que la dose maximale de 200 mg soit atteinte.

  18. JamesGag表示:

    best canadian online pharmacy: Online pharmacy USA – canadian pharmacy online

  19. Sup everyone! this has been a great place to explore new ideas. Really appreciate the value being shared.

  20. Williszew表示:

    https://mexicanpharminter.com/# mexican pharmacy online order

  21. PENIPU ONLINE表示:

    You can definitely see your expertise in the article you write.
    The arena hopes for more passionate writers such as you
    who aren’t afraid to mention how they believe.
    At all times follow your heart.

  22. Charles Wittl表示:

    You ought to take part in a contest for one of the greatest sites online.
    I’m going to highly recommend this blog!

  23. Williszew表示:

    https://mexicanpharminter.com/# mexican pharmacy online store

  24. Greate post. Keep posting such kind of info on your site.

    Im really impressed by your site.
    Hello there, You’ve done a fantastic job. I’ll definitely
    digg it and individually suggest to my friends. I’m sure they will be benefited from this site.

  25. international money transfers swift will be made from

    Wow! This blog looks exactly like my old one! It’s on a totally different topic but it has pretty much the same layout and design. Superb
    choice of colors!

  26. Eanreuf表示:

    Для успешного продвижения по карьере потребуется наличие официального диплома института. Купить диплом ВУЗа у сильной организации: rusd-diplomj.ru/kupit-nastoyashij-diplom-bistro-i-nadezhno/

發佈回覆給「Modafinil Provigil」的留言 取消回覆

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