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

  1. Stephenpem表示:

    http://buyprednisone.store/# 50mg prednisone tablet

  2. Charlesdix表示:

    https://amoxil.cheap/# how to buy amoxycillin

  3. Charlesdix表示:

    http://lisinopril.top/# lisinopril 30mg coupon

  4. DouglasSkild表示:

    The Comprehensive Manual to Gutter Installation, Rain Gutter Guard Setting up, and Rain Gutter Cleaning Services
    If you’re a owner of a house, you comprehend the value of upkeeping a functional gutter setup. Rain gutters serve an important role in protecting your home from water harm by channeling water from rainfall away from the roof and base. However, ensuring your gutters are in top condition requires more than just occasional cleansing. From rain gutter setting up to gutter protector setting up and rain gutter cleansing services, this comprehensive guide covers everything one require to know to keep your gutters in top shape.

    Gutter Installation
    Why Rain Gutters Matter
    Before we plunge into rain gutter setting up, let’s comprehend why gutters are essential for your home. Gutters help avert water harm by directing water from rainfall away from your house’s base, walls, and landscaping. Without adequate water drainage, rainwater runoff can lead to erosion, basement flooding, mold growth, and constructional damage.

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

    Gutter Materials
    When it comes to gutter materials, one have various options to choose 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 decorative flair to your home.

    DIY vs. Professional Installation
    While some house owners might try to set up 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 Installation
    The Importance of Gutter Guards
    Rain Gutter guards are an essential addition to any gutter system. These protective covers avert leaves, twigs, and debris from clogging your rain gutters, lowering the requirement for frequent cleaning and minimizing the risk of water damage to your home.

    Types of Rain 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 gutter while preventing leaves and debris from entering.
    Brush Inserts: Brush-style inserts fit inside the gutter and prevent 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 homeowners might attempt to set up rain 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.

    Rain Gutter Cleaning Assistance
    The Importance of Rain 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 gutter cleaning assistance can help stop these issues and extend the life of your gutters.

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

    Frequency of Gutter Cleaning
    The frequency of 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 protecting your home from water damage and preserving its structural integrity. Whether you require rain gutter installation, rain gutter guard installation, or rain 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.

  5. DavidRak表示:

    lasix 100 mg tablet Buy Furosemide lasix generic name

  6. สัมผัสความตื่นเต้นของโปเกม่อนกับโปเกม่อนออนไลน์!
    สนุกกับเกมคลาสสิคไพ่ไทยได้ทุกที่ทุกเวลา เล่นคนเดียวหรือเข้าร่วมเกมแบบผู้เล่นหลายคนและเชื่อมต่อกับเพื่อนๆ เสี่ยงโชคของคุณและดูว่าคุณสามารถเอาชนะเจ้ามือที่ป๊อกได้หรือไม่

    My homepage :: ป้อกเด้งออนไลน์

  7. DavidRak表示:

    furosemide 40mg Buy Lasix lasix uses

  8. DavidRak表示:

    can you buy lisinopril zestril coupon lisinopril online pharmacy

  9. DavidRak表示:

    ivermectin iv ivermectin oral 0 8 ivermectin lice

  10. JamesCof表示:

    amoxicillin 500 mg: generic amoxicillin cost – buy amoxicillin from canada

  11. JamesCof表示:

    ivermectin rx: minocin 50 mg for scabies – stromectol 3 mg tablet

  12. DavidRak表示:

    buy furosemide online Buy Lasix furosemide

  13. JamesCof表示:

    price for amoxicillin 875 mg: amoxicillin generic – amoxicillin generic brand

  14. JamesCof表示:

    amoxicillin 500 mg purchase without prescription: purchase amoxicillin online – buy amoxicillin canada

  15. DouglasSkild表示:

    Your Comprehensive Manual to Rain Gutter Installation, Gutter Guard Installation, and Gutter Cleaning Assistance
    If you’re an homeowner, one grasp the importance of maintaining an efficient rain gutter system. Gutters serve a vital role in safeguarding your home from water harm by directing water from rainfall away from the roof and base. However, ensuring your rain gutters are in top shape demands more than just periodic cleansing. From gutter setting up to rain gutter guard installation and rain gutter cleaning assistance, this complete guide addresses everything you need to understand to keep your gutters in optimal condition.

    Rain Gutter Setting up
    Why Gutters Matter
    Before we dive into gutter installation, let’s grasp why gutters are vital for your home. Rain gutters aid stop water harm by directing rainwater away from your home’s foundation, walls, and landscaping. Without proper drainage, water runoff can cause erosion, basement flooding, mold growth, and constructional harm.

    Signs You Require New Gutters
    Cracks or Rust: Visible cracks or rust spots suggest that your gutters are deteriorating and might need 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 home or basement flooding may indicate that your gutters are failing to do their job.
    Frequent Clogs: If your gutters are continuously clogged with debris, it may be time to invest in an updated rain gutter system that is easier to maintain.

    Gutter Materials
    When it comes to rain gutter materials, you have numerous options to select from:

    Aluminum: Lightweight, rust-resistant, and available 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 decorative flair to your house.

    DIY vs. Professional Installation
    While some house owners might 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 gutters are installed correctly and function optimally. Plus, hiring a professional can save you time and hassle in the long run.

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

    Types of Rain Gutter Guards
    Mesh Screens: Fine mesh screens allow 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 preventing 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 gutter guards block debris while allowing water to filter through.

    Professional Setting up vs. DIY
    While some homeowners may attempt to set up rain gutter guards themselves, professional installation 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.

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

    Signs You Need Rain Gutter Cleaning
    Visible Debris: If you notice leaves, twigs, or other debris in your gutters, it’s time for a cleansing.
    Water Overflow: Overflowing gutters during rainstorms suggest that they are clogged and need to be cleaned.
    Sagging Rain Gutters: Rain gutters that sag or pull away from the home might be weighed down by debris and require 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 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 shielding your house from water damage and preserving its structural integrity. Whether you require 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.

  16. JamesCof表示:

    furosemida: Buy Furosemide – lasix

  17. DavidRak表示:

    lasix uses Buy Furosemide furosemide 40mg

  18. our website表示:

    This web site definitely has all of the info I needed about this subject and
    didn’t know who to ask.

  19. ae casino表示:

    สวัสดีค่ะ! AE Gaming เป็นเว็บไซต์ที่มีเกมคาสิโนออนไลน์ที่น่าสนใจมากมายสำหรับผู้เล่นทุกคนในทุกวัยทุกเพศ ทั้งคาสิโนสด,
    สล็อตออนไลน์, และเกมโป๊กเกอร์ออนไลน์ คุณสามารถเข้าเล่นเกมได้ตลอดเวลาผ่านทางอุปกรณ์สมาร์ทโฟนหรือPC นอกจากนี้ AE Casino
    ยังมีโปรโมชั่นและโบนัสมากมายเพื่อเพิ่มโอกาสในการชนะเล่นเกมอีกด้วย สำหรับใครที่ชื่นชอบเสี่ยงโชคและคาสิโนออนไลน์ AE Gaming เป็นเว็บไซต์ที่คุณไม่ควรพลาดเลยค่ะ!

    ลองเข้าไปเล่นกันดูได้เลย!

  20. JamesCof表示:

    generic lisinopril: lisinopril 10 mg prices – lisinopril 10 mg coupon

  21. Wonderful goods from you, man. I have remember your stuff previous to and you are just too great.

    I actually like what you’ve got right here, certainly like what you’re
    stating and the way in which you assert it.
    You’re making it entertaining and you still care for to stay it sensible.
    I cant wait to learn much more from you. That is actually a wonderful website.

  22. JamesCof表示:

    ivermectin: ivermectin buy – where to buy ivermectin pills

  23. DavidRak表示:

    order lisinopril online us lisinopril 40 mg price prinivil 10 mg

  24. Для входа на зеркало официального сайта игрока не требуется учреждать дополнительное программное
    обеспечение или использовать
    ВПН, так как зеркала и официальный сайт имеют общую базу данных.
    Использование зеркала позволяет зараз получить доступ
    к аккаунту, а игрок может использовать собственный обычный логин и пароль.
    Компания-оператор казино добавляет слоты,
    игры и бонусы, что может
    ввергнуть к перегрузке сервера.
    В некоторых странах, включая Россию, онлайн-казино могут подвергаться
    блокировке в соответствии с местными нормами действующего законодательства.
    Кент казино – одинёхонек из ресурсов,
    кой подпадает под блокировки.

    Однако это не означает, что само казино прекращает свою работу, лишь определенный сайт становится недоступным.
    Поэтому игроки из других регионов и стран могут продолжать
    наигрывать без каких-либо
    проблем. При блокировке сайта аккаунт пользователя не затрагивается, все его данные находятся в полной безопасности.
    Кроме того, блокировка сайта не влияет на состояние игрового счета, если на нем поедать
    финансовые средства. В некоторых странах,
    включая Россию, онлайн-казино могут подвергаться блокировке в соответствии с местными нормами действующего
    законодательства. Кент казино – один-одинёхонек из ресурсов, кой
    подпадает под блокировки.
    Однако это не означает, что само казино прекращает свою работу, лишь определенный сайт становится недоступным.
    Поэтому игроки из других регионов и стран могут продолжать перекидываться без каких-либо проблем.
    При блокировке сайта аккаунт пользователя не затрагивается, все его данные находятся в полной безопасности.
    Кроме того, блокировка сайта не влияет на
    состояние игрового счета, если на нем
    кушать финансовые средства.
    Процедура верификации личности пользователя является обязательной для всех
    пользователей. Проверка личности пользователя осуществляется после регистрации.
    Для подтверждения предоставленной личной информации от игрока потребуется послать на адрес электронной почты
    администрации интернет-портала сканкопии или фото соответствующих
    документов. Дополнительно игрокам, которые планируют использовать банковскую карту выслать фото своей карты с
    двух сторон. Kent Casino — это новое и современное интернет-казино, которое предлагает своим
    клиентам вагон преимуществ.
    Одной из главных причин положительных отзывов об этом казино
    является вероятность мгновенных выплат.

    Администрация также обеспечивает высоченный уровень безопасности и защиты персональной информации клиентов.
    Кроме того, игроки в Kent Casino имеют доступ к игровым автоматам с
    высоким процентом отдачи, кой составляет от 96% до
    99%.

  25. DavidRak表示:

    buy prednisone online fast shipping prednisone otc uk where can i buy prednisone online without a prescription

  26. 20 Things That Only The Most Devoted Double Glazed Replacement Glass Near Me Fans
    Are Aware Of double Glazing Near me

  27. Awesome posts, Thank you!

  28. I like this site – its so usefull and helpfull.

    https://www.tvsudecka.pl

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

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