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,585,565 Responses

  1. Georgewhend表示:

    onlinepharmaciescanada com: Certified International Pharmacy Online – vipps approved canadian online pharmacy

  2. Montebeera表示:

    legal canadian pharmacy online InterPharmOnline.com best canadian online pharmacy

  3. Power Trades表示:

    An impressive share! I have just forwarded this onto a friend who has been doing a little research on this.

    And he actually ordered me breakfast because I discovered it for him…
    lol. So allow me to reword this…. Thank YOU for the meal!!
    But yeah, thanks for spending the time to discuss this topic here on your site.

  4. Georgewhend表示:

    canadian drug pharmacy: canada pharmacy no prescription – canadian neighbor pharmacy

  5. DonDonrob表示:

    darknet links https://github.com/nexusdarkrtv1u/nexusdark – dark web market list

  6. Champion Slots Казино — это место, где сбываются мечты о выигрыше. У нас представлены самые популярные игровые автоматы, а также эксклюзивные новинки. Любой посетитель может найти здесь игру по душе и насладиться атмосферой комфорта и азарта.

    Что делает Champion Slots особенным? Наше казино объединяет традиции и инновации, чтобы каждая минута в игре приносила удовольствие. К вашим услугам разнообразие игр на любой вкус. Кроме того, мы предлагаем увеличивают ваши шансы на успех, https://championslots-winpulse.autos/.

    Как выбрать идеальное время для игры? Самое лучшее время — это сейчас! Ваш успех уже ждет вас.

    Перед началом игры ознакомьтесь с правилами, чтобы избежать недоразумений.
    Используйте возможности VIP-программы, чтобы получить доступ к особым привилегиям и увеличить свои шансы на крупный выигрыш.
    Если вы только начинаете или давно не играли, демо-версии игр — это идеальный способ освежить навыки без риска.

  7. Georgewhend表示:

    canada pharmacy: most reliable canadian online pharmacies – my canadian pharmacy reviews

  8. Pingidiof表示:

    darknet markets onion https://github.com/aresonioncq0a7/aresonion – dark web drug marketplace

  9. Moses Parmely表示:

    “Failure is a great teacher and, if you are open to it, every mistake has a lesson to offer.” —Oprah Winfrey??????

  10. Aux doses thГ©rapeutiques, il n’a pas Г©tГ© associГ© Г  des abus et n’est pas une substance contrГґlГ©e. Le but initial pour lequel il a Г©tГ© dГ©veloppГ© Г©tait d’ГЄtre un agent d’Г©veil. Le modafinil a Г©tГ© dГ©veloppГ© comme traitement de la narcolepsie dans les annГ©es 1970. Le modafinil a des effets importants sur la substance noire et la rГ©gion tegmentale ventrale. Il a Г©tГ© dГ©montrГ© que le modafinil augmentait les niveaux d’acГ©tylcholine dans le cerveau et, par consГ©quent, Jouvet soupГ§onnait qu’il pourrait avoir la capacitГ© d’amГ©liorer le fonctionnement mental. Le modafinil est une substance contrГґlГ©e aux Г‰tats-Unis. Son mГ©canisme d’action est similaire Г  celui de l’amphГ©tamine, mais on considГЁre qu’il a un effet plus uniforme et plus durable. Puisqu’il a Г©tГ© dГ©montrГ© qu’il interfГЁre avec l’activitГ© des rГ©cepteurs des neurotransmetteurs, cela peut ГЄtre un moyen d’amГ©liorer l’Г©veil. Le modafinil est parfois associГ© au mГ©thylphГ©nidate, qui est disponible en vente libre sous le nom de Ritalin, pour lutter contre la somnolence diurne. Leur justification Г©tait le passage progressif Г  des processus d’ingГ©nierie et de production plus automatisГ©s sur le lieu de travail, qui avaient dГ©jГ  affectГ© les ouvriers d’usine. Il peut Г©galement exercer ses effets positifs via l’acГ©tylcholine. Cela rГ©veille le corps. Il doit ГЄtre pris le matin pour ГЄtre efficace. Le modafinil peut Г©galement ГЄtre utilisГ© comme activateur cognitif chez l’homme. https://nootropiquepharmacie.com/modiodal-100-mg/ Cependant, cette propriГ©tГ© n’a pas Г©tГ© reproduite chez l’homme. Le modafinil inhibe Г©galement l’activitГ© de la dopamine dans le cerveau et peut avoir un certain effet sur la dГ©pression clinique. Des Г©tudes ont Г©tГ© rГ©alisГ©es Г  des doses de 100 mg, 200 mg, 300 mg, 400 mg, 600 mg et 800 mg/jour. L’isomГЁre D du modafinil est prГ©sent Г  des concentrations beaucoup plus faibles et n’est responsable que d’environ 5 % des effets du modafinil. Il figure sur la liste des mГ©dicaments essentiels de l’Organisation mondiale de la santГ©, les mГ©dicaments les plus sГ»rs et les plus efficaces nГ©cessaires dans un systГЁme de santГ©. Le modafinil, vendu entre autres sous le nom de marque Provigil, est un stimulant du systГЁme nerveux central (SNC) utilisГ© pour traiter la somnolence due Г  la narcolepsie, les troubles du sommeil liГ©s au travail postГ© et l’apnГ©e obstructive du sommeil. Il devient un liquide jaune pГўle lorsqu’il est dissous dans l’eau et se mГ©lange complГЁtement au sang s’il n’est pas administrГ© immГ©diatement. En moyenne, un patch de 200 mg contient 165 mg de modafinil racГ©mique. Le modafinil est dГ©crit comme un inhibiteur “faible” du cytochrome P450 (CYP) 3A4. Le desmГ©thylmodafinil a une activitГ© pharmacologique similaire Г  celle du modafinil. Les autres noms du modafinil sont Provigil, Modalert, Provod, Provod-1, Dex-Modafinil et Armodafinil.

  11. Arthurhow表示:

    https://mexicanpharminter.com/# Mexican Pharm Inter
    canadianpharmacyworld

  12. I go to see day-to-day some web pages and blogs to read content,
    however this web site offers quality based content.

  13. Thanks for another magnificent post. Where else could anybody get that kind
    of information in such an ideal method of writing? I have a presentation next
    week, and I’m at the search for such info.

  14. Arthurhow表示:

    http://mexicanpharminter.com/# buying from online mexican pharmacy
    canadian pharmacy cheap

  15. JamesGag表示:

    IndiaMedFast.com: cheapest online pharmacy india – india pharmacy without prescription

  16. JamesGag表示:

    MexicanPharmInter: buying from online mexican pharmacy – mexican pharmacy online order

  17. Does your blog have a contact page? I’m having problems locating it but, I’d like to shoot you an email.
    I’ve got some recommendations for your blog you might be interested in hearing.
    Either way, great website and I look forward to seeing it
    improve over time.

  18. Arthurhow表示:

    https://mexicanpharminter.com/# Mexican Pharm Inter
    legitimate canadian online pharmacies

  19. Kudos. Lots of posts!

  20. Montebeera表示:

    india pharmacy without prescription online pharmacy india buying prescription drugs from india

  21. Arthurhow表示:

    https://interpharmonline.com/# my canadian pharmacy reviews
    canadian pharmacy uk delivery

  22. Hi there, of course this article is in fact fastidious and I have learned
    lot of things from it concerning blogging. thanks.

  23. JamesGag表示:

    mexican pharmacy online: mexican pharmacy online store – mexican pharmacy online store

  24. Arthurhow表示:

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

  25. Link - Elani表示:

    Digital casinos have reshaped the casino gaming market, providing a level of user-friendliness and range that physical venues are unable to replicate. Throughout the last ten years, millions of players worldwide have embraced the pleasure of internet-based gaming as a result of its ease of access, appealing qualities, and constantly growing range of offerings.

    If you’re a beginner with the world of virtual casino play or seek to explore proven options, why not become part of our growing community? It’s a place where gamblers post reviews, enabling you to improve your virtual play. Check out the community and see it here now:

    One of the most compelling reasons of digital gambling sites is the astounding diversity of choices at your disposal. Whether you like interacting with traditional fruit machine slots, trying out story-driven modern slot games, or testing your strategy in strategy-based games like Blackjack, digital casinos boast endless opportunities. A large number of platforms furthermore introduce live casino options, allowing you to participate with actual dealers and gaming peers, all while experiencing the authentic atmosphere of a brick-and-mortar establishment from the comfort of your home.

    Beyond variety, virtual gambling platforms stand out seamless entry.

  26. JamesGag表示:

    india online pharmacy store: IndiaMedFast.com – India Med Fast

  27. Georgewhend表示:

    buying prescription drugs from india: online medicine shopping in india – IndiaMedFast

發佈留言

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