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,245,376 Responses

  1. Узнай все о заболевание варикоцеле варикоцеле у мужчин симптомы

  2. MAKABANAIT表示:

    I am really enjoying the theme/design of your blog. Do you ever run into any
    web browser compatibility issues? A couple of my blog audience have complained about
    my site not operating correctly in Explorer but looks great in Chrome.
    Do you have any solutions to help fix this problem?

  3. It’s remarkable in support of me to have a web page, which is good in favor of my knowledge.
    thanks admin

  4. Тут можно преобрести сейф оружейный купить купить сейф оружейный

  5. Bradleygoath表示:

    max pharm priligy maxpharm buy priligy max pharm

  6. Always excited for The posts, because who else is going to make me feel this inadequately informed?

  7. Iyannaobesk表示:

    игровой аппарат fortune mouse gratis
    fortune mouse gratis на деньги

  8. Bradleygoath表示:

    where can i get clomid rexpharm can i get generic clomid without dr prescription

  9. Teodoro表示:

    You’re About To Expand Your Tread Mills Options treadmill at home
    (Teodoro)

  10. Bradleygoath表示:

    Priligy tablets Priligy tablets priligy maxpharm

  11. glucotrust表示:

    My brother suggested I would possibly like this website.
    He was totally right. This submit actually made my day.
    You cann’t imagine simply how a lot time I had spent for this
    information! Thank you!

  12. Casino表示:

    Good day! I could have sworn I’ve been to this website before but after checking through some of the post
    I realized it’s new to me. Anyhow, I’m definitely delighted I found it and I’ll be
    book-marking and checking back frequently!

  13. BrandenSlomy表示:

    dapoxetine price: dapoxetine price – buy priligy max pharm

  14. Dereketerm表示:

    prednisone 20mg price in india: buy prednisone – buy prednisone without prescription paypal

  15. врач нарколог на дом платный motik13.0pk.me/viewtopic.php?id=1995 .

  16. BrandenSlomy表示:

    max pharm: dapoxetine price – buy priligy

  17. нарколог на дом круглосуточно http://flanrp.rolevaya.com/viewtopic.php?id=146 .

  18. Nikefut表示:

    darknet market links deep web drug links drug markets dark web

  19. Bradleygoath表示:

    buy priligy priligy max pharm Priligy tablets

  20. Donaldter表示:

    На сегодняшний день самым эстетичным методом протезирования считаются безметалловые коронки. При этом под словом «керамика» подразумеваются самые разные химические соединения волгоград стоматология протезирование

  21. JacobLoody表示:

    кухни на заказ москва — Предлагаем изготовление кухонь под заказ в Москве с учетом ваших пожеланий.

  22. Theo表示:

    The Address Collection Case Study You’ll Never Forget 주소모음사이트 (Theo)

  23. Bradleygoath表示:

    azithromycin amoxicillin amoxil com pharm amoxil pharmacy

  24. StevenNub表示:

    prednisone buy: cheap prednisone – prednisone price canada

  25. Vortex Valor表示:

    I read this article completely about the comparison of
    most up-to-date and previous technologies, it’s remarkable article.

發佈留言

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