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,503 Responses

  1. JamesCof表示:

    prednisone no rx: generic prednisone 10mg – prednisone 10mg tabs

  2. LeonardFaulk表示:

    prednisone cost 10mg: prednisone 1 mg tablet – prednisone brand name in india

  3. DavidRak表示:

    where can you buy prednisone ordering prednisone 10mg prednisone daily

  4. DavidRak表示:

    where can i buy amoxicillin without prec where can i buy amoxicillin online amoxicillin 500 mg brand name

  5. Excellent post but I was wanting to know if you could write a litte
    more on this subject? I’d be very thankful if you could elaborate a little bit more.
    Many thanks!

  6. Charlesdix表示:

    https://buyprednisone.store/# prednisone 50 mg prices

  7. JamesCof表示:

    1 mg prednisone daily: prednisone 475 – prednisone 5 mg tablet rx

  8. Stephenpem表示:

    https://furosemide.guru/# furosemide 40mg

  9. JamesCof表示:

    stromectol order: ivermectin 400 mg brands – stromectol online

  10. Charlesdix表示:

    http://amoxil.cheap/# over the counter amoxicillin

  11. joker slot表示:

    Joker slot เป็นสล็อตออนไลน์ที่ได้รับความนิยมมากในประเทศไทย ผู้เล่นสามารถเพลิดเพลินและท้าทายโชคชะตาในการเล่นสล็อตได้ ไม่ว่าจะเป็นกราฟิกที่น่าตื่นตาตื่นใจ, การเล่นที่ง่ายดาย,
    หรือโบนัสและเงินรางวัลใหญ่ที่มอบให้อย่างจ generous.
    ทำให้ Joker slot ได้รับการรักษาของคนไทยอีกจำนวนมาก.
    ด้วยการเล่น Jokerslot, คุณสามารถทำเงินเสริมได้อย่างมีความสุขและระทึกขวัญ.

  12. JamesCof表示:

    lisinopril 20 mg buy: prices for lisinopril – lisinopril 10mg tablets price

  13. Jani Lain表示:

    A & H Garage Door Service
    943 S 40th St
    Springdale, AR 72762
    (479) 636-7658
    https://www.elitegaragedoornwa.com/

  14. Hi to all, how is the whole thing, I think every one is getting more from this
    website, and your views are pleasant designed for new viewers.

  15. I have been exploring for a bit for any high-quality articles or weblog
    posts on this sort of space . Exploring in Yahoo I
    eventually stumbled upon this site. Studying this info So i am
    happy to exhibit that I have a very excellent uncanny
    feeling I came upon exactly what I needed.
    I most definitely will make certain to do not forget this site and provides it a glance regularly.

  16. webpage表示:

    Hello there, You’ve done a great job. I’ll definitely digg it and personally suggest to my friends.

    I am sure they will be benefited from this site.

  17. DouglasSkild表示:

    Your Comprehensive Manual to Gutter Installation, Rain Gutter Protector Installation, and Rain Gutter Cleansing Services
    If you are a homeowner, you comprehend the value of maintaining an efficient rain gutter system. Rain gutters play a vital role in safeguarding your house from rainwater damage by channeling water from rainfall away from the roof and base. However, ensuring your rain gutters are in optimal shape requires more than just periodic cleaning. From rain gutter setting up to gutter protector installation and rain gutter cleansing assistance, this complete manual addresses everything one need to know to keep your gutters in optimal shape.

    Rain Gutter Setting up
    Why Rain Gutters Matter
    Before we plunge into rain gutter installation, let’s understand why gutters are crucial for your home. Rain gutters help stop water damage by directing water from rainfall away from your home’s foundation, walls, and landscaping. Without adequate drainage, rainwater runoff can lead to wear and tear, basement flooding, mold growth, and structural damage.

    Signs You Require New Gutters
    Cracks or Rust: Visible cracks or rust spots suggest that your gutters are deteriorating and may require to be replaced.
    Sagging or Pulling Away: Rain gutters that sag or pull away from the home are not effectively directing rainwater away and ought to be replaced.
    Water Damage: Water stains on the exterior of your house or basement flooding may indicate that your gutters are not functioning properly to do their job.
    Frequent Clogs: If your rain gutters are constantly clogged with debris, it might be time to invest in a new gutter system that is easier to maintain.

    Rain Gutter Materials
    When it comes to gutter materials, one have numerous options to choose from:

    Aluminum: Lightweight, rust-resistant, and accessible in a variety of colors.
    Vinyl: Affordable, easy to set up, and low maintenance.
    Steel: Durable and suitable for regions with harsh weather conditions.
    Copper: Elegant, long-lasting, and adds a decorative touch to your home.

    DIY vs. Professional Installation
    While some homeowners might try to install rain gutters themselves, it’s often best to leave this job to the professionals. Professional rain gutter installers have the experience, tools, and expertise to ensure that your gutters are installed correctly and operate optimally. Plus, hiring a professional can save you time and hassle in the long run.

    Gutter Guard Setting up
    The Importance of Rain Gutter Guards
    Gutter guards are an important addition to any gutter system. These protective covers stop leaves, twigs, and debris from clogging your rain gutters, minimizing the requirement for regular cleaning and minimizing the risk of water damage to your house.

    Types of Gutter Guards
    Mesh Screens: Fine mesh screens permit water to flow through while blocking debris.
    Reverse Curve: These gutter guards feature a curved surface that directs water into the rain gutter while preventing leaves and debris from entering.
    Brush Inserts: Brush-style inserts fit inside the rain gutter and stop leaves from accumulating while allowing water to flow freely.
    Foam Inserts: Foam gutter guards block debris while allowing water to filter through.

    Professional Setting up vs. DIY
    While some house owners might try to set up rain gutter guards themselves, professional setting up is often recommended. Professional installers can ensure that rain gutter guards are properly fitted and securely attached, reducing the risk of debris buildup and water damage.

    Gutter Cleaning Services
    The Importance of Gutter Cleaning
    Regular rain gutter cleaning is essential for maintaining a functional gutter system. Over time, leaves, twigs, and debris can accumulate in your gutters, leading to clogs and water overflow. Professional gutter cleaning services can help avert these issues and extend the life of your rain gutters.

    Signs You Require Rain Gutter Cleaning
    Visible Debris: If you observe leaves, twigs, or other debris in your gutters, it’s time for an cleansing.
    Water Overflow: Overflowing gutters during rainstorms suggest that they are clogged and require to be cleaned.
    Sagging Rain Gutters: Rain gutters that sag or pull away from the home may be weighed down by debris and need cleaning.
    Gutter cleaning service

    Frequency of Rain Gutter Cleaning
    The frequency of rain gutter cleaning depends on several factors, including the surrounding vegetation, climate, and rain gutter guard installation. In general, it’s recommended to clean your rain gutters at least twice a year, ideally in the spring and fall, to remove seasonal debris buildup.

    Conclusion
    Maintaining a functional rain gutter system is essential for shielding your home from water damage and preserving its structural integrity. Whether you require gutter installation, gutter guard installation, or gutter cleaning services, investing in professional assistance can save you time, money, and hassle in the long run. By prioritizing gutter, you can ensure that your house remains safe, dry, and protected for years to come.

  18. JamesCof表示:

    lasix 40 mg: Buy Furosemide – buy lasix online

  19. You’ve made some really good points there. I looked on the net to
    learn more about the issue and found most individuals will go along with your views on this site.

  20. Passion the site– extremely user pleasant and great deals to see!

    https://iotwock.info

  21. Its not my first time to pay a visit this web site, i am browsing this
    web site dailly and take nice information from here daily.

  22. JamesCof表示:

    amoxicillin 500mg price canada: amoxicillin 500mg capsules price – buy amoxicillin online no prescription

  23. 10 Myths Your Boss Has Concerning Window Glass Replacement cost of replacement windows uk

  24. I’ve read some excellent stuff here. Certainly price bookmarking for revisiting.
    I surprise how a lot attempt you put to create this sort of excellent informative site.

  25. Stephenpem表示:

    http://buyprednisone.store/# prednisone 10mg prices

  26. discuss表示:

    Thаnk you, I’ve recentⅼy been searchinbg for infoгmation aƅout thіѕ
    topic fоr ages and youurs iss tthe best I have
    found outt tiⅼl now. Bսt, wһat concerning the bottom line?
    Are you certain in гegards tо the supply?

    Here is my site: discuss

  27. JamesCof表示:

    buy lisinopril online no prescription india: where to buy lisinopril without prescription – lisinopril 2.15 mg

  28. notabug.org表示:

    Why Upvc Windows Repairs Isn’t A Topic That People Are Interested In. upvc window repair
    (notabug.org)

  29. Aw, this was a very nice post. Taking the time and
    actual effort to produce a really good article… but what can I say… I put things off a lot and don’t manage to get anything done.

    Also visit my web page – http://top.stargardzki.stargard.pl

發佈留言

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