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,588,787 Responses

  1. WilburGlile表示:

    Get the best odds, instant withdrawals & deposits, 24/7 customer service and refer bonus. Enjoy safe and secure betting with Stake786. stake 786 bet

  2. MorganThymn表示:

    top 10 pharmacies in india: Indian pharmacy online – India pharmacy ship to USA

  3. Just how ⅼong has it been since no less 4 of yoᥙr numbers were
    chosen as winners in the еnergy ball selection? Are yօu still playing the same numbers hoping things will
    change? Why are you torturing your self like when?
    Did you know that there are three guidelines you have to follow in ordeг to pick winning Powerball numbеrs; and if you do not follօw those
    guidelines you’re just throwing away moneу?

    Ken: The lot of hard thought ɑnd lateral thinking. It helped that my late father the brilliant optical engineer, aⅼong with many of his analytical mathematical abilitieѕ rubbed off
    me! When i found the “eureka” solution that perceived
    to work, I spеnt exercise proɡram couple of yearѕ researcһing and ϲhеcking it.
    Although at period I had computers may very well have sped
    the whole resеarch process up, the һoneѕt Lotto System doesn’t actually work on patteгned or computed phone numbers.

    So it had to be achіeved by hand. Took a whereas.

    Yes, it is important. It is only those who are lazy or possibly incapable ⲟf working the аctual Powerball Lottery
    numbers who just walk in a retailer’s shop, drop
    their cash and go hoping that heaven will open and shower
    grace and blessing on their scalр. It doesn’t work ⅼike whօm.
    If you are good in prayers, remember several
    types of other because they came from might be intɑct with God and looking out to be blessed with that same money
    too. Ought to you be God whаt an indivіⅾual do?

    Studies have shown that much of people that win Powerball are actually worѕe off 3
    years down the track thɑn what they were when they won. How
    can this be you may ask? If theу don’t understɑnd how to using money.
    They’re buying bigger houses, take out bigger
    mortgages and treat friends and family to expensiѵe trinkets.

    In the long run they generаte a lifestyle tһat needs
    them november 23 Powerbaⅼl every 5 extended. Sorry
    – Not possible.

    Tһе Hoosieг Lotteгy that uses Indіana State’s nickname, contains a
    6/48. Michigan ᒪottery іs 6/47, Arizona
    Lottery and Missouri Lottery are 6/44, Maryland Lottery is
    6/43, and Coloradо Lottery is 6/42. Match it up to the Florida Sweepstakes.

    State lotto games, aⅼong with the national Mega Lottο, ɑre really picked ɑ neԝ massive random number generator.
    Mathematically, there is no scientific method to predict the followіng set of random numbers that is availaЬle up.
    Whiϲh isn’t where it boils down to belief in lucҝy numbers with no scientifіc chеk
    out numbers whіch can be drawn.

    Be creative іn seⅼecting your lotterу numbers.
    Ꮇost people tend attain their own favorite numbers to select
    such as anniversariеs or birth dates back. However, this
    sort of method choosing lottery numbers actually limitѕ your actions.

    The dates only cover numbers from 1 to 31 while actually you still need a much bigger
    numbегs than most people. Another reason an individual
    should avoid this actuaⅼity there undoubtedly are lot the task out there who aⅼso do thе ѕame thing whenever you do.
    Gгeat for you . start believe about differently to get the winner.

    my web site: ซื้อหวยลาว

  4. sweet bonanza表示:

    This design is steller! You obviously know how to keep a reader amused.
    Between your wit and your videos, I was almost moved to start my own blog (well, almost…HaHa!) Great job.
    I really loved what you had to say, and more
    than that, how you presented it. Too cool!

  5. WilburGlile表示:

    Get the best odds, instant withdrawals & deposits, 24/7 customer service and refer bonus. Enjoy safe and secure betting with Stake786. stake786 login

  6. Keep on working, great job!

  7. NovusX表示:

    I truly love your site.. Excellent colors & theme. Did you build this website yourself?
    Please reply back as I’m hoping to create my very own site and would like to know where you got this from or just what the theme is called.
    Kudos!

  8. MorganThymn表示:

    northwest pharmacy canada: Canadian Pharmacy AAPD – thecanadianpharmacy

  9. Charlescek表示:

    mexican pharmacy acp п»їbest mexican online pharmacies buying prescription drugs in mexico

  10. qq1221表示:

    I must thank you for the efforts you’ve put in writing this site.

    I’m hoping to view the same high-grade content from you later
    on as well. In truth, your creative writing abilities has inspired me to get my own blog now 😉

  11. RandallLoone表示:

    canada ed drugs: Canadian Pharmacy AAPD – safe reliable canadian pharmacy

  12. A person essentially help to make seriously articles I would state.

    This is the very first time I frequented your website page and
    to this point? I amazed with the analysis you made to make this
    particular post incredible. Fantastic activity!

  13. Does your website have a contact page? I’m having problems locating
    it but, I’d like to send you an email. I’ve got some recommendations for your
    blog you might be interested in hearing. Either way,
    great site and I look forward to seeing it improve over time.

  14. 5play1ruDup表示:

    На 5play1.ru ты найдешь все самые свежие игры с русским языком. Мы добавляем новые игры с русским интерфейсом каждый день, чтобы ты мог наслаждаться игрой в родной для тебя языке. Поставь на паузу сложности с языком в играх — заходи и скачивай игры с русским языком прямо сейчас!

  15. RandallLoone表示:

    pharmacy rx world canada: canadian pharmacy in canada – the canadian drugstore

  16. RandallLoone表示:

    Online medicine home delivery: Indian pharmacy international shipping – Indian pharmacy international shipping

  17. Hey very interesting blog!

  18. homepage表示:

    Since the blockchain is decentralized, the support team may not have the authority to resolve every problem.

  19. phising表示:

    These are truly great ideas in regarding blogging. You have touched
    some pleasant points here. Any way keep up wrinting.

  20. Sazravw表示:

    Мы предлагаем дипломы любых профессий по доступным тарифам. Стоимость зависит от выбранной специальности, года получения и образовательного учреждения. Стараемся поддерживать для клиентов адекватную политику тарифов. Для нас очень важно, чтобы дипломы были доступны для большого количества граждан. где купить диплом колледжа

  21. Thank you for the good writeup. It in truth used to be a amusement account it.
    Glance advanced to more brought agreeable from you!
    By the way, how can we be in contact?

  22. darknet market https://kingdommarketdarknet.com/ – best darknet markets

  23. MorganThymn表示:

    Best Indian pharmacy: IndianPharmacyAbp – IndianPharmacyAbp

  24. Jerold表示:

    This piece of writing is truly a good one it assists new the web viewers, who are wishing for
    blogging.

  25. FNDavidemert表示:

    bitcoin dark web https://firstdarkmarket.com/ – darknet market lists

  26. zabaioc01表示:

    Very good article. I definitely appreciate this website.
    Keep writing!

    Also visit my web blog – zabaioc01

發佈留言

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