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,624,398 Responses

  1. see this here表示:

    Great post. I was checking constantly this blog and I’m impressed!
    Very useful info particularly the last part 🙂 I care
    for such information a lot. I was seeking this certain information for a long time.
    Thank you and good luck.

  2. Dereketerm表示:

    buy priligy max pharm: dapoxetine online – Priligy tablets

  3. StevenNub表示:

    prednisone 20 mg without prescription: prednisone – where can i order prednisone 20mg

  4. Dereketerm表示:

    dapoxetine price: priligy max pharm – buy priligy max pharm

  5. StevenNub表示:

    amoxicillin 500 mg tablets: amoxil – amoxicillin cephalexin

  6. Drugs information sheet. Generic Name.
    meaning of atorvastatin calcium
    Everything trends of medicine. Read information here.

  7. There are various tools and websites that affirmation to allow users to view private Instagram
    profiles, but it’s important to entre these afterward caution. Many of
    these tools can be unreliable, may require
    personal information, or could violate Instagram’s terms of service.

    Additionally, using such tools can compromise your own security or guide to scams.

    The safest and most ethical artifice to view a private instagram viewer free profile is to send
    a follow demand directly to the user. Always prioritize privacy
    and love in your online interactions.

  8. Danieljek表示:

    can we buy amoxcillin 500mg on ebay without prescription http://prednisoneraypharm.com/# where to buy prednisone in australia

  9. SubPaish表示:

    स्लॉट गेम ऑनलाइन perimatch casino online games

  10. Danieljek表示:

    buy cheap amoxicillin online http://clomidrexpharm.com/# buying generic clomid

  11. Composite Door Replacement Lock Tools To Help You Manage Your Everyday Lifethe Only Composite Door
    Replacement Lock Trick That Everyone Should Learn composite door replacement lock

  12. find out here表示:

    When I originally commented I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get
    three emails with the same comment. Is there any way you can remove people
    from that service? Thanks!

  13. Hi, Neat post. There is an issue with your website in web explorer, might check this?

    IE still is the market chief and a large
    portion of other folks will omit your fantastic writing due
    to this problem.

  14. Danieljek表示:

    amoxicillin 500mg price in canada http://prednisoneraypharm.com/# prednisone 10mg prices

  15. discover this表示:

    Very nice post. I just stumbled upon your blog and wished to
    say that I have truly enjoyed surfing around your blog posts.

    In any case I will be subscribing to your feed and I hope you write
    again soon!

  16. BrandenSlomy表示:

    online order prednisone: prednisone ray pharm – buy prednisone online uk

  17. Легко ли быть наблюдателем,
    когда вокруг творится зло и нельзя вмешаться, навести порядок, защитить?
    Главный герой этого романа –
    дон Румата (землянин Антон), который попадает на
    планету Арканар с экспериментальным миром.

    На этой планете царит средневековая жестокость,
    фальшь и борьба за власть.
    Но Румата не должен вмешиваться.
    Он ученый, который проводит эксперимент.

    Однако человек в нем берет вверх над ученым,
    сердце побеждает рассудок.
    Разве можно спокойно наблюдать, как зло побеждает добро, как
    талант растаптывается, а справедливости не существует?
    Главному герою это не удается…
    Трудно быть Богом

  18. BrandenSlomy表示:

    prednisone 20: ray pharm – buy 40 mg prednisone

  19. StevenNub表示:

    where can i buy clomid without a prescription: rex pharm – order generic clomid without rx

  20. Generally I don’t read article on blogs, but I would like to say that this write-up very forced
    me to take a look at and do so! Your writing style
    has been amazed me. Thanks, quite great post.

  21. StevenNub表示:

    generic prednisone for sale: generic Prednisone – prednisone cost in india

  22. Danieljek表示:

    buy amoxicillin online mexico https://priligymaxpharm.com/# buy dapoxetine online

  23. Protein Bars – Draught Beer Really Healthful? 중구오피 (historydb.date)

  24. Danieljek表示:

    order amoxicillin online no prescription https://amoxilcompharm.com/# amoxicillin no prescription

  25. StevenNub表示:

    10mg prednisone daily: prednisone – how can i get prednisone online without a prescription

  26. Why Double Glazing Windows Maidstone Can Be More Risky Than You Thought misted window maidstone

  27. Bradleygoath表示:

    amoxicillin 500 mg online Amoxicillin for sale buy amoxil

  28. Danieljek表示:

    amoxicillin 500 https://amoxilcompharm.com/# cost of amoxicillin 875 mg

發佈回覆給「StevenNub」的留言 取消回覆

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