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,367,730 Responses

  1. BarryDof表示:

    http://rybelsus.shop/# buy rybelsus online

  2. Clay Newland表示:

    The 10 Most Scariest Things About French Style American Fridge Freezer French Style American Fridge Freezer

  3. Darrellrit表示:

    Patient pill information. Medication trends described.
    clarithromycin usa
    Get medication details. Comprehensive medicine overview.

  4. Plant-based vapes have a host of prospective benefits.

    Also visit my blog … what beers are vegan uk

  5. Jonah Peck表示:

    A Trip Back In Time A Conversation With People About Butt Plug Near Me 20 Years Ago butt anal plug

  6. RamonRek表示:

    rybelsus price: rybelsus price – semaglutide tablets

  7. BarryDof表示:

    https://rybelsus.shop/# buy rybelsus online

  8. Frankevild表示:

    https://rybelsus.shop/# semaglutide tablets

  9. RamonRek表示:

    ozempic coupon: buy ozempic – buy ozempic

  10. Noble表示:

    20 Things You Should Ask About Ethanol Fireplace Before
    Buying It ethanol fireplace fuel; Noble,

  11. See What Lightweight Mobility Scooters For Sale Tricks The Celebs Are Utilizing lightweight mobility scooters For sale

  12. Профессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
    Мы предлагаем: сервисные центры по ремонту техники в волгограде
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  13. Bookmarks表示:

    Solar energy is clean. Gas plans are a lot simpler.

    Feel free to surf to my site – Bookmarks

  14. پت شاپ表示:

    It’s actually very difficult in this busy life to listen news on TV, thus
    I just use world wide web for that reason, and take the most up-to-date information.

  15. What NOT To Do In The Sports Toto Near Me Today Industry 스포츠토토 사이트 (0lq70ey8yz1b.com)

  16. Ludie Kleiber表示:

    What Is Wall Mounted Fireplace? What Are The Benefits And How To Use It electric fires (Adan)

  17. 15 Things You’ve Never Known About Rolls Royce Phantom Key rolls royce phantom key Price

  18. The 10 Most Scariest Things About Blown Double Glazing Repairs Near Me
    Double Glazing Repairs Near Me

  19. Frankevild表示:

    http://ozempic.art/# buy cheap ozempic

  20. Frankevild表示:

    https://rybelsus.shop/# rybelsus price

  21. Woah! I’m really enjoying the template/theme of this
    blog. It’s simple, yet effective. A lot of times it’s hard to get that “perfect balance” between usability
    and visual appeal. I must say you’ve done a very good
    job with this. Also, the blog loads very fast for me
    on Firefox. Outstanding Blog!

  22. What Freud Can Teach Us About Realistic Sex Doll Silicone most realistic silicone sex dolls (squareblogs.net)

  23. 10 Things You’ll Need To Know About Couches On Sale Couches On Sale Near Me

  24. Jeremypag表示:

    ozempic generic ozempic generic buy cheap ozempic

  25. заказы на выведение обрабатываются в ручном
    режиме, поэтому такой перевод вполне может занимать больше времени,
    1вин чем зачисление.

    Feel free to visit my homepage … https://1win-n-9lgc.buzz/

  26. RamonRek表示:

    buy ozempic: ozempic – buy ozempic pills online

  27. bookmarks表示:

    Below you find the currently cheapest energy tariffs.

    My web site :: bookmarks

發佈留言

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