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,631,333 Responses

  1. Stephenpem表示:

    http://amoxil.cheap/# amoxicillin 500mg cost

  2. Charlesdix表示:

    http://lisinopril.top/# zestoretic coupon

  3. Charlesdix表示:

    http://stromectol.fun/# buy ivermectin for humans australia

  4. Great blog you have got here.. It’s difficult to find high-quality writing
    like yours these days. I really appreciate individuals like you!
    Take care!!

  5. JamesCof表示:

    prednisone prescription for sale: order prednisone 100g online without prescription – online prednisone

  6. Spot on wіth this write-up, I aƄsolutely Ƅelieve tһis web site needs a lоt more attention. I’ll рrobably be returning tߋ ѕee more, tһanks for the info!

    Here is my blog – online betting

  7. DavidRak表示:

    prednisone cream prednisone purchase canada over the counter prednisone medicine

  8. slot rajacuan表示:

    Thank you for the good writeup. It in reality was once a amusement account it.
    Look advanced to far delivered agreeable from you!
    However, how could we keep in touch?

  9. JamesCof表示:

    ivermectin 0.2mg: order stromectol online – ivermectin 50ml

  10. Charlesdix表示:

    http://stromectol.fun/# cost of ivermectin lotion

  11. ShayneLip表示:

    Статистика личных встреч по футболу, прогнозы и аналитика матчей онлайн Футбол в России: последние новости РПЛ и других лиг России

  12. JamesCof表示:

    generic amoxicillin cost: buy amoxil – where to get amoxicillin over the counter

  13. DavidRak表示:

    amoxicillin 500 coupon amoxicillin without a prescription amoxicillin 500mg price canada

  14. Stephenpem表示:

    https://buyprednisone.store/# prednisone over the counter uk

  15. SuperƄ websitе you have here but I was curious about if you knew of
    any user discussion forums that cover the same topics dіscuѕsed here?
    I’d really like to be a part οf community where I can get sᥙggesti᧐ns from other қnowledgeable individuals that share the same interеst.
    If you haѵe any recommendations, pleɑse let mе ҝnow.

    Thanks!

    Review my web blog – DedicatedProxies.Net

  16. Thank you for the good writeup. It in fact was a amusement account it.
    Look advanced to far added agreeable from you!
    However, how can we communicate? https://biowiki.Clinomics.com/index.php/Les_Meilleurs_Sites_D_Agences_Immobili%C3%83%C2%A8res_Sur_Le_Qu%C3%83_bec

  17. JamesCof表示:

    lisinopril 0.5 mg: lisinopril 20 mg pill – 16 lisinopril

  18. Stephenpem表示:

    https://amoxil.cheap/# amoxicillin 500 mg without a prescription

  19. Stephenpem表示:

    http://amoxil.cheap/# amoxicillin 500mg capsules antibiotic

  20. ShayneLip表示:

    Статистика личных встреч по футболу, прогнозы и аналитика матчей онлайн футбольная статистика магия данных н

  21. Charlesemasy表示:

    Хостинг в Беларуси
    Разместить сайт или проект любой сложности
    виртуальный сервер
    Наша миссия состоит в том, чтобы предоставить частным лицам и организациям надежные хостинговые решения, которые способствуют успеху и росту в Интернете. Вот уже более 15-ти лет мы обеспечиваем стабильный и прочный «фундамент» для тысяч сайтов по всей Беларуси и за её пределами
    Хостинг сайтов
    Все необходимые инструменты для быстрой и стабильной работы ваших сайтов
    Выбрать хостинг сайта – занятие, с которым справится не каждый клиент. Пользователям приходится проводить оценку критериям и характеристикам ресурса.
    Наши специалисты всегда готовы помочь с этим не легким выборам хостинга для размещения сайта.

  22. JamesCof表示:

    buy amoxicillin online without prescription: order amoxicillin online no prescription – amoxicillin 500 mg without a prescription

  23. DavidRak表示:

    furosemide 100 mg furosemide furosemide

  24. JamesCof表示:

    prednisone tablets canada: prednisone pill prices – prednisone 20 mg purchase

  25. Today, I went to the beachfront with my children. 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 placed 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 completely off topic but I had to tell someone!

  26. Bright Stone Pressure & Soft Washing
    7965 Edgemont Rd
    Greers Ferry, AR 72067
    (501) 825-7188
    pressure washing

  27. RonaldBatty表示:

    The Comprehensive Manual to Rain Gutter Setting up, Rain Gutter Guard Installation, and Gutter Cleansing Assistance
    If you’re a owner of a house, one grasp the importance of maintaining a functional rain gutter setup. Gutters play a crucial role in protecting your house from rainwater damage by directing rainwater away from the roof and foundation. However, ensuring your gutters are in optimal condition demands more than just occasional cleansing. From rain gutter setting up to gutter protector installation and gutter cleaning services, this complete manual addresses everything you need to know to keep your rain gutters in optimal shape.

    Gutter Installation
    Why Rain Gutters Are Important
    Before we dive into gutter installation, let’s comprehend why rain gutters are essential for your home. Rain gutters help stop rainwater damage by directing rainwater away from your house’s base, walls, and landscaping. Without proper drainage, rainwater runoff can cause wear and tear, basement flooding, mold growth, and constructional 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 efficiently directing water away and ought to be replaced.
    Water Damage: Water stains on the exterior of your home or basement flooding may indicate that your gutters are failing to do their job.
    Frequent Clogs: If your gutters are constantly clogged with debris, it might be time to invest in an updated rain gutter system that is easier to upkeep.

    Gutter Materials
    When it comes to gutter materials, you have several 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 appropriate for regions with harsh weather conditions.
    Copper: Elegant, long-lasting, and adds a decorative touch to your home.

    DIY vs. Professional Setting up
    While some homeowners may attempt to install rain gutters themselves, it’s often preferable 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.

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

    Types of Gutter Guards
    Mesh Screens: Fine mesh screens allow water to flow through while blocking debris.
    Reverse Curve: These 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 prevent leaves from accumulating while allowing water to flow freely.
    Foam Inserts: Foam rain gutter guards block debris while allowing water to filter through.

    Professional Setting up vs. DIY
    While some homeowners 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, minimizing the risk of debris buildup and water damage.

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

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

    Frequency of Rain Gutter Cleaning
    The frequency of rain gutter cleaning depends on several factors, including the surrounding vegetation, climate, and 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 gutter system is essential for shielding your house from water damage and preserving its structural integrity. Whether you require rain gutter installation, rain 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.

發佈留言

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