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,366,487 Responses

  1. HaroldBig表示:

    rybelsus pill: cheapest rybelsus pills – rybelsus coupon

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

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

  4. HaroldBig表示:

    ozempic: ozempic online – Ozempic without insurance

  5. iumeuddlb表示:

    Even though you will not find sure straight win football predictions, the following advice can still come in handy for betting of all kinds. To begin with, don’t bet with your heart and just put money on the team you support, and ensure that you read carefully the provided soccer prediction to make sure of your selection. It can also be helpful to look at the team news to see how strong a line-up is going to be fielded. On top of that, this research will improve your chances of winning but just remember that upsets will happen in the not totally predictable world of sports betting. All our sure football prediction is safe and reliable this why we remain the only site that offers 90 accurate football predictions for today and weekend. Our 100 sure football predictions offered by football experts and tipsters is one of the reasons we are the best prediction site or the prediction site that never loses. If you ever think of surest prediction site in the world or any hot prediction site that offer 99 percent football prediction Trustpredict is the best site for sure prediction.
    https://web-wiki.win/index.php?title=Superbowl_mvp_bets
    Updated odds to win the Masters (via BetMGM) Odds and lines subject to change. 21+ (18+ NH WY). AZ CO CT IL IN IA LA MI NH NJ NY OR PA TN VA WV WY only. Eligibility restrictions apply. See DraftKings sportsbook for full terms and conditions. Hard Rock Bet sportsbook gives Koepka the sixth-best odds (+1750), the same odds as fellow major champion Jordan Spieth. If a sportsbook listed Woods at +2500 to slip on the green jacket, a $100 bet on Tiger to win the Masters would pay out $2,600 for a net profit of $2,500. Use our betting odds calculator to calculate your future winnings. Remember that the Masters starts this Thursday. The honorary starters tee off at 8:15 a.m. Eastern. The featured groups start an hour later. To get your prep on, check out the world rankings here. And the Masters already has its pairings for the first and second rounds. Check it here.

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

  7. uk88表示:

    Usually I do not read post on blogs, however I would like to
    say that this write-up very forced me to try and do
    it! Your writing taste has been surprised me. Thanks,
    very nice article.

  8. BarryDof表示:

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

  9. BarryDof表示:

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

  10. BarryDof表示:

    http://ozempic.art/# Ozempic without insurance

  11. I all the time used to read article in news papers but now as I am a user of internet so from
    now I am using net for posts, thanks to web.

  12. Frankevild表示:

    https://rybelsus.shop/# cheapest rybelsus pills

  13. In some cases, they might stop working to act according
    to the trust fund maker’s exact assumptions.

  14. HaroldBig表示:

    semaglutide tablets: buy semaglutide pills – rybelsus cost

  15. Brigette表示:

    10 Things You Learned In Kindergarden Which Will Aid You
    In Obtaining Freestanding Electric Fireplace wall fires (Brigette)

  16. HaroldBig表示:

    rybelsus coupon: buy semaglutide pills – buy semaglutide pills

  17. Jeremypag表示:

    buy semaglutide online semaglutide cost semaglutide online

  18. Amazing! This blog looks exactly like my old one!
    It’s on a totally different topic but it has pretty much the
    same page layout and design. Wonderful choice of colors!

  19. HaroldBig表示:

    rybelsus cost: cheapest rybelsus pills – rybelsus coupon

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

  21. HaroldBig表示:

    cheapest rybelsus pills: semaglutide tablets – semaglutide online

  22. BarryDof表示:

    https://rybelsus.shop/# semaglutide cost

  23. Hmm it looks like your site ate my first comment (it was extremely long) so I guess I’ll just
    sum it up what I wrote and say, I’m thoroughly enjoying your blog.

    I too am an aspiring blog blogger but I’m still new to everything.
    Do you have any helpful hints for newbie blog writers?

    I’d genuinely appreciate it.

  24. I just like the helpful information you provide to your articles.
    I will bookmark your blog and test again right here frequently.
    I’m slightly sure I’ll be told a lot of new stuff proper here!
    Best of luck for the next!

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

  26. HaroldBig表示:

    Ozempic without insurance: Ozempic without insurance – buy ozempic pills online

  27. Thank you, I have just been searching for info
    approximately this topic for ages and yours is the greatest
    I’ve found out till now. However, what about the conclusion?
    Are you positive in regards to the source?

    Visit my page :: คอร์สดำน้ำ

發佈留言

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