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,247,116 Responses

  1. BrandenSlomy表示:

    priligy max pharm: priligy – Priligy tablets

  2. StevenNub表示:

    buy dapoxetine online: buy priligy – buy priligy max pharm

  3. StevenNub表示:

    Priligy tablets: priligy – buy priligy

  4. porn comic表示:

    Pretty nice post. I just stumbled upon your weblog and wished
    to say that I have really enjoyed surfing around your blog posts.

    In any case I will be subscribing to your rss feed
    and I hope you write again very soon!

  5. промокод робокасса на 5000 promokod-robokassa.ru .

  6. StevenNub表示:

    can you buy amoxicillin over the counter: buy amoxil online – buy amoxicillin over the counter uk

  7. Luella Ingram表示:

    Phone repair costs can really add up! I’ve been researching ways to save money on repairs, and samsung repair has some excellent suggestions worth checking out

  8. StevenNub表示:

    prednisone over the counter: buy prednisone – prednisone 5 mg tablet without a prescription

  9. BrandenSlomy表示:

    generic for amoxicillin: amoxil com pharm – buy amoxicillin 250mg

  10. Dereketerm表示:

    cheap priligy: priligy max pharm – priligy max pharm

  11. BrandenSlomy表示:

    amoxicillin 500: Com Pharm – amoxicillin price canada

  12. koibuaya.com表示:

    Hi! Someone in my Facebook group shared this site with us so I came to look it over.
    I’m definitely loving the information. I’m book-marking
    and will be tweeting this to my followers! Excellent blog and brilliant design.

  13. I always emailed this web site post page to all my friends, because if like to read it after that my
    friends will too.

  14. Admiring the hard work you put into your blog
    and in depth information you offer. It’s nice to come across a blog every once in a
    while that isn’t the same out of date rehashed material. Wonderful read!
    I’ve bookmarked your site and I’m including your RSS feeds to
    my Google account.

  15. Dereketerm表示:

    medicine amoxicillin 500mg: cheap amoxil – amoxicillin 500 coupon

  16. Patrickwraxy表示:

    В неожиданном повороте событий мемкоины вытеснили биткоин из топа самых обсуждаемых криптоактивов в социальных сетях. По данным аналитической платформы Santiment, такие токены как PNUT, PEPE и DOGE заняли лидирующие позиции, оттеснив первую криптовалюту на седьмое место по популярности new best meme 2024

  17. えろ 人形or passive-aggressive behavior.These subtle signs of jealousy can create tension and mistrust in the relationship.

  18. Nikefut表示:

    dark web markets dark web market list https://darknetmarketstore.com/ – dark market list

  19. Hey there, I think your site might be having browser
    compatibility issues. When I look at your website
    in Firefox, it looks fine but when opening in Internet Explorer, it has some overlapping.
    I just wanted to give you a quick heads up!
    Other then that, terrific blog!

  20. Davidhiz表示:

    Цель каждого специалиста нашей команды – забота о ментальном здоровье людей через предоставление как можно более доступной и качественной медицинской помощи, а также через психопросветительскую деятельность и дестигматизацию ментальных расстройств https://cse.google.com.sg/url?sa=t&url=https://empathycenter.ru

發佈留言

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