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,365,141 Responses

  1. Hello, after reading this amazing article i am too cheerful
    to share my experience here with colleagues.

  2. Scot表示:

    You substantially decrease risks as well when you have a professional do the treatment.

  3. RamonRek表示:

    buy semaglutide online: rybelsus pill – rybelsus cost

  4. Near Me表示:

    Five Killer Quora Answers On Ghost Immobiliser Installers Near Me
    Near Me

  5. CJC-1295 is an artificial peptide created to boost the production of growth hormonal agent (GH) in the body (2 ).

  6. Jeremypag表示:

    rybelsus pill rybelsus cost buy semaglutide online

  7. RamonRek表示:

    ozempic cost: ozempic online – Ozempic without insurance

  8. Quick meal planning tips for all dietary needs at dessert recipes [https://vkusno-gotovim-xshk.blogspot.com/] for better results!

    I’ve been surfing online more than 4 hours today, yet I never found any
    interesting article like yours. It’s pretty worth
    enough for me. Personally, if all web owners and bloggers made good content as you did, the web
    will be a lot more useful than ever before.

  9. Frankevild表示:

    https://ozempic.art/# ozempic coupon

  10. Jeremypag表示:

    buy rybelsus online rybelsus coupon buy semaglutide online

  11. Frankevild表示:

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

  12. RamonRek表示:

    rybelsus price: rybelsus pill – buy semaglutide online

  13. Jeremypag表示:

    buy semaglutide online rybelsus pill buy rybelsus online

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

  15. Greetings from Los angeles! I’m bored at work so I decided to browse your blog on my iphone during lunch break.
    I really like the information you present here and can’t wait
    to take a look when I get home. I’m surprised at how fast your blog loaded on my phone ..
    I’m not even using WIFI, just 3G .. Anyways, good site!

  16. GeorgeGed表示:

    best betting promo codes: A promotional offer from betting sites, providing bonuses like free bets, deposit bonuses, or enhanced odds to incentivize users.

  17. Certainly, angiotensin II can act at considerate nerve closings to advertise
    neurotransmission [Reid, 1992]

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

  19. HaroldBig表示:

    semaglutide tablets: buy rybelsus online – rybelsus price

  20. 이를 비교하여 가짜를 비아그라 구매판별할 수 있습니다. 비아그라 구매4. 가격 비교: 가격비아그라 구매이 너무

  21. RamonRek表示:

    buy semaglutide online: rybelsus coupon – buy semaglutide online

  22. Raina表示:

    And if you’re planning on sitting tight, you’ll get to take pleasure in a classic, valuable
    home.

  23. In almost all instances, Mod GRF 1-29 ought to be utilized in favor over CJC1295Dac.

  24. Beware Of These “Trends” About Leather Couch And Loveseat Leather sofa set (images.google.co.il)

  25. I’m not sure where you’re getting your information, but great topic.
    I needs to spend some time learning more or understanding more.
    Thanks for great info I was looking for this info for my mission.

  26. Living Will表示:

    It is not acceptable for MetLife or its employees or representatives to provide legal advice.

  27. excellent publish, very informative. I’m wondering why the other
    specialists of this sector don’t notice this. You must proceed your writing.
    I’m confident, you have a great readers’ base already!

  28. Jeremypag表示:

    ozempic coupon ozempic cost ozempic online

  29. Visit here表示:

    Thanks for sharing such a nice idea, paragraph is fastidious, thats why i have read
    it completely

  30. Why Nespresso Machine Will Be Your Next Big Obsession? Nespresso Professional machine

發佈留言

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