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,524,113 Responses

  1. осмотр гинеколога порно https://www.ginekolog-rukoeb1.ru .

  2. Pflanzen Blog表示:

    Appreciation to my father who told me concerning this
    website, this web site is really amazing.

  3. MarkWat表示:

    Приветствую. Может кто знает, где найтиразные блоги о займах? Сейчас читаю – blackdiamond-val.ru

  4. Porterfax表示:

    Mega India Pharm MegaIndiaPharm MegaIndiaPharm

  5. Charleskepsy表示:

    pharmacy discount coupons https://familypharmacy.company/# online pharmacy delivery usa

  6. MichaelGeony表示:

    cheapest prescription pharmacy https://discountdrugmart.pro/# discount drug mart pharmacy

  7. CharlesSycle表示:

    Интернет – магазин керамический плитки и керамогранита, для любых поверхностей и помещений Керамогранит для ванной

  8. Davidnof表示:

    deep web search https://github.com/darkwebwebsites/darkwebwebsites – black internet dark web market list

  9. this means you have more chances to win if you bet money with a coefficient 1.5 in front of competitors 15-fold. you can see that https://manuelplgb11100.blogscribble.com/32890472/aviator-game-review-is-it-worth-playing in bets on smaller numbers will not be be as impressive as when betting on highest multipliers.

  10. 1 vin_fqSi表示:

    вывод денег с 1win https://www.bbcc.com.kg .

  11. Charleskepsy表示:

    online pharmacy discount code https://easycanadianpharm.com/# easy canadian pharm

  12. MichaelGeony表示:

    international pharmacy no prescription http://xxlmexicanpharm.com/# best online pharmacies in mexico

  13. 1 vin_emSi表示:

    1win официальный 1win официальный .

  14. Davidmoits表示:

    easy canadian pharm: onlinecanadianpharmacy 24 – easy canadian pharm

  15. Charleskepsy表示:

    canada drugs coupon code https://familypharmacy.company/# Online pharmacy USA

  16. WillieRap表示:

    easy canadian pharm: easy canadian pharm – best mail order pharmacy canada

  17. Viagra 25 mg, achat viagra en pharmacie, Etnografiadigitale. Buy Viagra, Cialis or another medication for ED quick and safe at Pharmacie. Acheter Misoprostol en ligne, acheter Cytotec 100 mcg sens. Pharmacie en ligne France: acheter des medicaments generiques. Bienvenue sur pharmacie -eu.org votre pharmacie en ligne France Belgique. Buy real viagra.Healthy Bones, Healthy Bones, Free Courier Delivery. Sildenafil, pfizer achat meilleur generique vente sans ordonnance.Achat du. Dapoxetine buy online en ligne a bon compte.Sans ordonnance dapoxetine. https://eurogeneriqueetfrance.com/azathioprine/ Bon Marche Azathioprine Drogue

  18. hello there and thank you for your information ? I?ve definitely picked uup anything new from right here.
    I did howevber expertise a few technical points using this website, as I experienced too reload the weeb site
    lots of times previous to I could get it to load properly.
    I had been wondering iif yojr web host is OK? Not that I am
    complaining, but slow loading instances times will very frequently
    affect your placement in google and can damage your high quality score iif ads
    and marketing with Adwords. Welll I?m adding this RSS
    to my e-mail and can look out for a lot more of your respective exciting content.
    Make sure you update this again soon..

    My bog post; https://www.applysarkarinaukri.com/secondary-classes-for-school-all-with-the/

  19. lotto champ表示:

    Great post. I used to be checking continuously this weblog
    and I am inspired! Very helpful info particularly the final
    part 🙂 I maintain such info a lot. I was looking for this certain info for a long time.
    Thank you and good luck.

  20. Charleskepsy表示:

    online pharmacy no prescription http://familypharmacy.company/# Online pharmacy USA

發佈留言

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