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,630,400 Responses

  1. Heya! I know this is kind of off-topic however I had to ask.

    Does building a well-established website such as yours require
    a massive amount work? I am completely new to writing a blog however I do write in my journal every day.
    I’d like to start a blog so I will be able to share my personal experience and views online.
    Please let me know if you have any kind of ideas or tips for new aspiring blog owners.
    Appreciate it!

  2. You made your point!

  3. DavidRak表示:

    amoxicillin online canada amoxicillin 250 mg price in india amoxicillin buy no prescription

  4. sport bet表示:

    Fantastic goods fгom you, man. І’ve understand yoᥙr stuff previous to and you are ϳust too gгeat.
    I really lіke whаt yоu’ve acquired һere, ceгtainly like ѡhat
    yoᥙ are stating and the way in wһіch y᧐u sаy it.
    You make it entertaining and yоu ѕtill care for
    tⲟ keep it sensible. I can not wait to reɑd far mоre from yοu.
    Ƭhis iѕ actually a gгeat web site.

    Ꮮook into my webpage: sport bet

  5. RonaldBatty表示:

    Your Complete Manual to Rain Gutter Installation, Rain Gutter Guard Setting up, and Gutter Cleansing Services
    If you’re a owner of a house, one understand the significance of upkeeping an efficient rain gutter system. Gutters serve an important function in shielding your home from rainwater damage by directing rainwater away from the top and base. However, making sure your gutters are in optimal condition requires more than just periodic cleaning. From rain gutter installation to rain gutter protector installation and rain gutter cleaning services, this complete manual covers everything you require to be aware of to keep your rain gutters in optimal condition.

    Rain Gutter Installation
    Why Gutters Are Important
    Before we dive into rain gutter installation, let’s understand why rain gutters are crucial for your house. Rain gutters aid avert rainwater harm by directing water from rainfall away from your house’s foundation, walls, and landscaping. Without adequate water drainage, rainwater runoff can cause wear and tear, basement flooding, mold growth, and structural harm.

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

    Gutter Materials
    When it comes to rain gutter materials, you have several options to select 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 decorative flair to your house.

    DIY vs. Professional Setting up
    While some house owners may try to set up 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 Protector Setting up
    The Importance of Gutter Guards
    Gutter guards are an essential addition to any rain gutter system. These protective covers avert leaves, twigs, and debris from clogging your gutters, reducing the need for regular cleaning and reducing 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 rain gutter guards feature a curved surface that directs water into the 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 may attempt to install rain gutter guards themselves, professional setting up is often recommended. Professional installers can ensure that rain gutter guards are properly fitted and securely attached, minimizing the risk of debris buildup and water damage.

    Rain Gutter Cleansing Services
    The Importance of Gutter Cleaning
    Regular 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 assistance can help avert these issues and extend the life of your gutters.

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

    Frequency of Rain Gutter Cleaning
    The frequency of gutter cleaning depends on several factors, including the surrounding vegetation, climate, and rain gutter guard installation. In general, it’s recommended to clean your 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 safeguarding your home from water damage and preserving its structural integrity. Whether you need rain gutter installation, rain gutter guard installation, or gutter cleaning assistance, investing in professional assistance can save you time, money, and hassle in the long run. By prioritizing maintenance, you can ensure that your home remains safe, dry, and protected for years to come.

  6. JamesCof表示:

    amoxicillin 50 mg tablets: amoxicillin canada price – amoxicillin from canada

  7. I got this web page from my friend who told me
    regarding this web site and now this time I am browsing this website and reading very informative
    articles or reviews here.

  8. Stephenpem表示:

    http://amoxil.cheap/# generic amoxil 500 mg

  9. Colin Skalski表示:

    You made the point.

  10. misted表示:

    10 Reasons Why People Hate Double Glazing Window Repair misted

  11. I have been exploring for a little for any high quality articles or blog posts on this sort of space .
    Exploring in Yahoo I finally stumbled upon this website.

    Reading this information So i am glad to convey that I’ve an incredibly just right
    uncanny feeling I came upon exactly what I needed. I such a lot undoubtedly will make
    certain to do not put out of your mind this website and provides
    it a look on a constant basis.

  12. slot rajacuan表示:

    I used to be able to find good advice from your articles.

  13. Charlesdix表示:

    http://furosemide.guru/# buy furosemide online

  14. This Story Behind Replacement Window Handle Will Haunt You Forever!
    upvc replacement Window handles

  15. Today, I went to the beach with my kids. I found a sea shell and gave it to
    my 4 year old daughter and said “You can hear the ocean if you put this to your ear.”
    She put the shell to her ear and screamed. There was a hermit crab inside
    and it pinched her ear. She never wants to go back! LoL I know this is totally off topic but I had to tell someone!

    my website; http://new.wroclawski.wroclaw.pl

  16. DavidRak表示:

    lasix 40mg lasix 100 mg tablet furosemide 40mg

  17. Chas表示:

    The Most Effective Reasons For People To Succeed At The Double
    Glazing Window Repairs Industry upvc repairs (Chas)

  18. DavidRak表示:

    prednisone 2.5 tablet buy prednisone mexico prednisone 20 mg prices

  19. JamesCof表示:

    lisinopril 12.5 mg price: buy cheap lisinopril 40mg – lisinopril 5 mg canada

  20. JamesCof表示:

    lisinopril canada: buy lisinopril 10 mg – lisinopril tablet 40 mg

  21. The 10 Scariest Things About Replacement Saab Key Saab Keys Replacement

  22. LGO 4D表示:

    I’m not that much of a online reader to be honest but your blogs really nice,
    keep it up! I’ll go ahead and bookmark your site to come back
    down the road. Cheers

  23. I think the admin of this web site is in fact working
    hard in support of his website, because here every material is quality based
    information.

  24. RonaldBatty表示:

    The Complete Guide to Rain Gutter Setting up, Gutter Guard Setting up, and Rain Gutter Cleansing Services
    If you are an owner of a house, one comprehend the significance of upkeeping an functional gutter system. Rain gutters play an important role in safeguarding your house from rainwater harm by directing rainwater away from the roof and base. However, ensuring your gutters are in optimal condition demands more than just occasional cleaning. From rain gutter installation to rain gutter protector setting up and rain gutter cleaning assistance, this complete manual covers everything one require to understand to keep your gutters in optimal shape.

    Gutter Setting up
    Why Rain Gutters Are Important
    Before we plunge into rain gutter installation, let’s comprehend why gutters are vital for your home. Rain gutters help avert water harm by directing water from rainfall away from your home’s base, walls, and landscaping. Without adequate water drainage, rainwater runoff can cause wear and tear, basement flooding, mold growth, and constructional damage.

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

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

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

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

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

    Types of Rain Gutter Guards
    Mesh Screens: Fine mesh screens permit water to flow through while blocking debris.
    Reverse Curve: These rain gutter guards feature a curved surface that directs water into the rain gutter while stopping 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 rain gutter guards block debris while allowing water to filter through.

    Professional Installation vs. DIY
    While some house owners may attempt to set up gutter guards themselves, professional installation is often recommended. Professional installers can ensure that rain gutter guards are properly fitted and securely attached, minimizing the risk of debris buildup and water damage.

    Gutter Cleansing Services
    The Importance of Rain Gutter Cleaning
    Regular rain gutter cleaning is essential for maintaining a functional rain gutter system. Over time, leaves, twigs, and debris can accumulate in your gutters, resulting to clogs and water overflow. Professional rain gutter cleaning services can help prevent 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 indicate that they are clogged and require to be cleaned.
    Sagging Gutters: Gutters that sag or pull away from the house might be weighed down by debris and need cleaning.
    gutter guard company

    Frequency of 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 gutters at least twice a year, ideally in the spring and fall, to remove seasonal debris buildup.

    Conclusion
    Maintaining a functional gutter system is essential for shielding your home from water damage and preserving its structural integrity. Whether you need rain gutter installation, rain gutter guard installation, or gutter cleaning assistance, 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 secured for years to come.

  25. DondeGo.es表示:

    Hello there, I found your blog by means of Google while looking for a related matter, your site came up, it appears to be like good.
    I have bookmarked it in my google bookmarks.
    Hello there, just became aware of your blog via Google,
    and located that it is really informative. I am going to
    be careful for brussels. I will appreciate should you continue this in future.

    Numerous people might be benefited from your writing.
    Cheers!

  26. DavidRak表示:

    medicine amoxicillin 500mg amoxicillin in india amoxicillin 500mg price canada

  27. DavidRak表示:

    prinivil 25mg zestril tablet generic zestoretic

  28. DavidRak表示:

    lasix generic Buy Lasix furosemide 40 mg

發佈留言

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