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,243,312 Responses

  1. Lazrnee表示:

    Легальная покупка диплома ПТУ с сокращенной программой обучения

    mf.getbb.ru/viewtopic.php?f=28&t=1001

  2. Blakesmema表示:

    http://www.webcocktail.ru — Узнайте о лучших решениях для вашей кухни на нашем сайте.

  3. 5 Laws That Will Help The Good Accident Lawyers Industry
    Good Accident Lawyers Near Me

  4. What’s The Job Market For Ultra Lightweight Folding Wheelchairs Professionals?
    ultra lightweight folding wheelchairs

  5. Great content, Regards.

  6. Узнай все о двустороннее варикоцеле варикоцеле симптомы

  7. Dereketerm表示:

    can i purchase amoxicillin online: amoxil – 875 mg amoxicillin cost

  8. BrandenSlomy表示:

    how to get cheap clomid for sale: clomid rex pharm – cost clomid without rx

  9. Very good blog you have here but I was curious if you knew of any discussion boards that
    cover the same topics talked about here? I’d really love to be
    a part of group where I can get suggestions from other knowledgeable people that share the same interest.
    If you have any suggestions, please let me know. Thank you!

  10. 10 Reasons You’ll Need To Learn About All Crypto Casinos Best Crypto Casino

  11. Dereketerm表示:

    can i purchase clomid now: rex pharm – where can i get generic clomid without rx

  12. Your Family Will Be Thankful For Having This Male.Masturbator Mens masturbator

  13. Iyannaobesk表示:

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

  14. BrandenSlomy表示:

    buy prednisone 10mg online: prednisone ray pharm – buy prednisone 1 mg mexico

  15. StevenNub表示:

    amoxicillin discount: Amoxicillin buy online – prescription for amoxicillin

  16. нарколог на дом круглосуточно https://zavitai.mybb.social/viewtopic.php?id=89 .

  17. Dereketerm表示:

    prednisone steroids: prednisone – prednisone prescription drug

  18. Pretty great post. I simply stumbled upon your blog and wished to mention that I have really loved surfing around your blog posts.
    In any case I’ll be subscribing on your rss feed and I am hoping you write once more very soon!

  19. Dereketerm表示:

    buy amoxicillin online with paypal: amoxil – buy amoxicillin 500mg uk

  20. Get More Info表示:

    Hello there I am so grateful I found your blog page, I really found you by accident, while I was researching
    on Aol for something else, Nonetheless I am here now and would just like to say thanks for a remarkable post and a all round entertaining blog (I
    also love the theme/design), I don’t have
    time to go through it all at the minute but I have book-marked it and also included your RSS feeds, so when I have time I will be back to read a great deal more, Please do
    keep up the fantastic work.

  21. StevenNub表示:

    amoxicillin order online no prescription: amoxil com pharm – amoxicillin discount

  22. Lazryfj表示:

    Как купить аттестат 11 класса с официальным упрощенным обучением в Москве
    meat.ntnn.ru/personal/profile/index.php?register=yes

  23. Lazrlri表示:

    Всё, что нужно знать о покупке аттестата о среднем образовании
    newspromworld.ru/poluchite-diplom-byistro-i-bez-stressa

  24. JacobLoody表示:

    кухни на заказ москва — Индивидуальные кухни на заказ с доставкой по Москве.

  25. Узнай все о варикоцеле 2 степени варикоцеле левого яичка

  26. Узнай все о варикоцеле причины возникновения варикоцеле и потенция

發佈留言

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