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,625,336 Responses

  1. Georgewhend表示:

    india pharmacy without prescription: online pharmacy india – order medicines online india

  2. PENIPU ONLINE表示:

    Nice respond in return of this difficulty with real arguments and describing all on the
    topic of that.

  3. JamesGag表示:

    canadianpharmacyworld: online canadian pharmacy no prescription – medication canadian pharmacy

  4. japanese porn表示:

    Hi, this weekend is nice in support of me, since this time i am reading this wonderful informative article
    here at my house.

  5. Georgewhend表示:

    order medicines online india: lowest prescription prices online india – online medicine shopping in india

  6. mitolyn scam表示:

    Howdy! I’m at work surfing around your blog from my new iphone!

    Just wanted to say I love reading through your blog and look forward to all your posts!
    Carry on the outstanding work!

  7. Arthurhow表示:

    https://indiamedfast.shop/# buying prescription drugs from india
    canadian drugstore online

  8. Williszew表示:

    https://interpharmonline.shop/# canadian pharmacy 365

  9. JamesGag表示:

    IndiaMedFast: lowest prescription prices online india – IndiaMedFast

  10. JamesGag表示:

    india pharmacy without prescription: india online pharmacy store – cheapest online pharmacy india

  11. DonDonrob表示:

    onion dark website https://github.com/nexusdarkrtv1u/nexusdark – best darknet markets

  12. Williszew表示:

    https://mexicanpharminter.com/# reliable mexican pharmacies

  13. Notably, Mystake.com does not impose any deposit or withdrawal fees, although it’s essential for players to be
    aware that certain payment providers may levy fees.

  14. JamesGag表示:

    IndiaMedFast: india online pharmacy store – lowest prescription prices online india

  15. Williszew表示:

    https://indiamedfast.shop/# india pharmacy without prescription

  16. JamesGag表示:

    mexican pharmacy online order: Mexican Pharm Inter – mexican pharmacy online store

  17. Il a vendu son brevet Г  Roussel US en 1989. Le modafinil a Г©tГ© cliniquement Г©valuГ© pour le traitement de la somnolence excessive dans plusieurs Г©tudes. L’efficacitГ© du modafinil n’est pas prouvГ©e pour amГ©liorer les fonctions cognitives chez les personnes en bonne santГ©. Il a Г©tГ© constatГ© qu’il augmente la vigilance et amГ©liore la capacitГ© d’attention. En tant que tel, il s’agit d’un mГ©dicament potentiellement dangereux avec un faible indice thГ©rapeutique en raison du potentiel de syndrome sГ©rotoninergique, dans lequel les niveaux de sГ©rotonine sont Г©levГ©s au repos, entraГ®nant l’apparition de symptГґmes physiologiques tels qu’une transpiration excessive, une rigiditГ© musculaire, une hyperthermie, des bouffГ©es vasomotrices, frissons, confusion et agitation. Il n’a pas d’effet stimulant. Le modafinil augmente probablement l’Г©veil en amГ©liorant l’activitГ© cГ©rГ©brale, mais le mГ©canisme exact reste incertain. Les effets secondaires graves peuvent inclure des rГ©actions allergiques telles que l’anaphylaxie et le syndrome de Stevens-Johnson, ainsi que des hallucinations chez les personnes ayant des antГ©cГ©dents de psychose. Le modafinil est un ingrГ©dient pharmaceutique actif. En outre, il a Г©tГ© rapportГ© que le modafinil augmentait les concentrations de mГ©thylphГ©nidate et de lisdexamfГ©tamine. Le modafinil est un stimulant non amphГ©tamine. Il peut ГЄtre utilisГ© pour les personnes souffrant de crampes nocturnes aux jambes, du syndrome des jambes sans repos (SJSR) et les personnes souffrant de somnolence diurne excessive due Г  l’apnГ©e obstructive du sommeil. https://nootropiquepharmacie.com/adrafinil-achat/ Les patients doivent ГЄtre munis d’une ordonnance d’un mГ©decin et d’un document mГ©dical valide contenant cette ordonnance. La sociГ©tГ© pharmaceutique franГ§aise a Г©tГ© le fabricant de Provigil et l’a vendu dans plus de 70 pays. Le modafinil amГ©liore l’attention et la concentration en se liant aux systГЁmes de dopamine et d’histamine du cerveau. Au Royaume-Uni, le modafinil est disponible en tant que mГ©dicament gГ©nГ©rique, qui est approuvГ© pour le traitement de la somnolence diurne excessive. Bien que l’on pense que ces actions contribuent aux effets d’amГ©lioration des performances du modafinil, elles peuvent Г©galement expliquer certains des effets secondaires du mГ©dicament, tels que la suppression de l’Г©nergie et de l’appГ©tit. Le modafinil n’est pas un remГЁde contre la narcolepsie. En 2017, c’Г©tait le 205e mГ©dicament le plus prescrit aux Г‰tats-Unis, avec plus de 1,7 million d’ordonnances. Pris par voie orale, le mГ©dicament est pris en une seule dose de 200 Г  400 mg le matin. La libГ©ration de modafinil est normalement d’environ trois heures. Le modafinil est Г©galement vendu sous la marque Provigil, Zembrin et la marque locale Efrel.

  18. Georgewhend表示:

    lowest prescription prices online india: IndiaMedFast – India Med Fast

  19. Arthurhow表示:

    https://interpharmonline.shop/# buy prescription drugs from canada cheap
    canadian pharmacy near me

  20. Arthurhow表示:

    https://indiamedfast.shop/# india pharmacy without prescription
    safe canadian pharmacy

  21. I’m not sure why but this website is loading extremely slow for me. Is anyone else having this problem or is it a problem on my end? I’ll check back later and see if the problem still exists.

  22. I loved as much as you will receive carried out right here.

    The sketch is tasteful, your authored material stylish.

    nonetheless, you command get bought an nervousness over that you wish be delivering the following.
    unwell unquestionably come more formerly again since exactly the same nearly
    a lot often inside case you shield this hike.

  23. Arthurhow表示:

    http://indiamedfast.com/# online medicine shopping in india
    legal to buy prescription drugs from canada

  24. Cazrgtq表示:

    Приобрести диплом ВУЗа по невысокой цене возможно, обращаясь к надежной специализированной фирме. Мы готовы предложить документы Институтов, которые находятся в любом регионе РФ. diplomk-vo-vladivostoke.ru/diplom-kupit-visshee-obrazovanie

  25. Hello! For you I am Muhib ullah. Feel free to surf to my blog
    post – Colorado Springs Speeding Ticket Attorney

  26. pdacenter.ru – сервис по ремонту бытовой техники
    Ремонт фотовспышек в Перми в официальном сервисном центре PDACENTER.
    Наши инженеры выполняют ремонт любой сложности по дотупным ценам!

  27. Arthurhow表示:

    https://interpharmonline.shop/# 77 canadian pharmacy
    reputable canadian online pharmacies

  28. Montebeera表示:

    online medicine shopping in india IndiaMedFast IndiaMedFast.com

  29. Pingidiof表示:

    dark market url https://github.com/aresonioncq0a7/aresonion – darknet markets onion address

發佈留言

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