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,372,306 Responses

  1. HaroldBig表示:

    rybelsus cost: rybelsus coupon – rybelsus pill

  2. I all the time emailed this webpage post page to
    all my associates, because if like to read it after that my friends
    will too.

    Look into my page Therapy in Pensacola

  3. I’m impressed, I have to admit. Rarely do
    I encounter a blog that’s both educative and interesting, and let me tell you, you have hit the nail on the
    head. The problem is an issue that not enough folks are speaking intelligently about.
    Now i’m very happy that I came across this during my hunt for something relating to this.

  4. Guide To Lexus Replacement Key Fob: The Intermediate Guide In Lexus Replacement Key Fob lexus Replacement Key (glamorouslengths.com)

  5. this post表示:

    Wow, this paragraph is fastidious, my younger
    sister is analyzing such things, thus I am going to convey her.

  6. food表示:

    Fantastic blog! Do you have any hints for aspiring writers?
    I’m hoping to start my own blog soon but
    I’m a little lost on everything. Would you advise starting with a free platform like WordPress
    or go for a paid option? There are so many options out there that I’m
    totally overwhelmed .. Any tips? Cheers!

  7. If some one wishes expert view regarding blogging afterward i suggest
    him/her to pay a quick visit this blog, Keep up the
    fastidious work.

  8. HaroldBig表示:

    ozempic generic: ozempic cost – ozempic online

  9. Great blog here! Also your site loads up fast!
    What host are you using? Can I get your affiliate
    link to your host? I wish my website loaded up as quickly as yours lol

    Here is my web site Best Florida Divorce Attorneys

  10. Frankevild表示:

    https://rybelsus.shop/# rybelsus coupon

  11. HaroldBig表示:

    ozempic generic: buy cheap ozempic – Ozempic without insurance

  12. HaroldBig表示:

    rybelsus coupon: rybelsus cost – semaglutide online

  13. Moreover, Melanotan II reveals guarantee as a treatment option for people with erectile dysfunction (ED).

  14. Jeremypag表示:

    cheapest rybelsus pills semaglutide tablets rybelsus cost

  15. BarryDof表示:

    http://rybelsus.shop/# semaglutide tablets

  16. Franklin Area Probate Court Robert G. Montgomery started among the state’s first court-run mediation programs soon after taking
    the bench in 2011.

  17. Clarkwer表示:

    Выше этношоп НашаМебель делает отличное предложение широкий подбор кухонь, коие помогут сделать уют а также удобство в течение вашем обиталище http://www.notahye4kuhnishki.ru/.

  18. memek表示:

    Its such as you read my mind! You seem to know so much
    about this, like you wrote the ebook in it or something.
    I feel that you just can do with some p.c. to force the message
    home a little bit, however instead of that, this is wonderful blog.

    An excellent read. I will definitely be back.

  19. Celsa表示:

    9 Things Your Parents Teach You About Upvc Window Repairs upvc window repair (Celsa)

  20. HaroldBig表示:

    rybelsus cost: semaglutide tablets – rybelsus cost

  21. Inviertas表示:

    I love your blog.. very nice colors & theme. Did you create this website yourself or did you hire someone to do
    it for you? Plz respond as I’m looking to design my own blog and
    would like to know where u got this from. cheers

    Also visit my web page: Inviertas

  22. rimailxib表示:

    The forex market is managed by a global network of institutions based in four major forex trading hubs in various time zones: London, New York, Sydney, and Tokyo. Because there is no central location, you may trade forex 24 hours a day, five days a week. Here, we’ll give a brief overview of the history of foreign exchange, review why someone might want to trade currencies, explore the forex market as a whole, consider the pros and cons of forex trading, and list and define some of the more common forex trading terms. Finally, we’ll offer answers to some of the more commonly asked questions about forex trading. This website is using a security service to protect itself from online attacks. The action you just performed triggered the security solution. There are several actions that could trigger this block including submitting a certain word or phrase, a SQL command or malformed data.
    http://www.servinord.com/phpBB2/profile.php?mode=viewprofile&u=650300
    The New Zealand dollar and the American dollar can be active sometimes from 10 pm to 7 am GMT, but the best time to trade the pair is between midnight to 2 am, from 6 am to 8 am, and between noon and 5 pm. The NZD USD pairing is often called the Kiwi pair. It accounts for almost 2% of the total trading turnover. #1 Mobile App by ForexBrokers © ActionForex © 2024 All rights reserved. These pairs are popular, but experience lower trading volumes than major pairs.  Forex traders utilize discipline and consistency in their trading. Here’s some expert tips to kickstart your forex trading: Top LosersWhich currency pairs have lost the most today? Losers refers to the currency pairs that had a negative percentage price movement since the previous day.

  23. Jeremypag表示:

    ozempic online buy ozempic buy cheap ozempic

  24. If you desire to increase your experience only keep visiting this web page and be updated with the latest news posted here.

    Feel free to visit my blog … Adoption Attorney in Florida

  25. Step By Step Summary About Seo Company Strategies 구글 백링크

  26. megaweb4.com表示:

    Aw, this was a really nice post. Spending some time and actual effort to
    produce a top notch article… but what can I say… I put things off a lot and never manage to get nearly anything done.

    my web site megaweb4.com

  27. Frankevild表示:

    http://ozempic.art/# ozempic coupon

  28. Frankevild表示:

    https://rybelsus.shop/# buy semaglutide pills

  29. HaroldBig表示:

    rybelsus coupon: rybelsus coupon – semaglutide online

  30. Franklyn表示:

    They are made an application for a specified time daily,
    and results become noticeable over a couple of weeks.

發佈留言

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