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,529,032 Responses

  1. 15 Incredible Stats About Programing Keys transponder key programmer

  2. Why ADHD Diagnosis UK Is Fast Becoming The Hottest Trend
    Of 2023 how to get diagnosed with adhd as a woman

  3. Thanks for sharing your thoughts on 252สล็อต. Regards

  4. my vegas slots on facebook login
    real money online casino in pa
    slot machine zapper for sale australia

  5. Don’t Stop! 15 Things About Car Locksmiths Near Me We’re
    Tired Of Hearing Car Lock Smith

  6. Diplomi_dyma表示:

    купить диплом медицинского вуза купить диплом медицинского вуза .

  7. Istanbul_zvst表示:

    Подробный обзор Istanbul International Airport, развитие аэропорта на протяжении лет.
    Интересные факты о Istanbul International Airport, о которых вы не знали.
    Строительство Istanbul International Airport, которые невозможно не отметить.
    Что ждет аэропорт в ближайшие годы, направления роста и совершенствования.
    Что делает аэропорт уникальным, какие услуги понравятся каждому.
    istanbul international airport taxi istanbul international airport taxi .

  8. Nine Things That Your Parent Teach You About Upvc Window Repair upvc Window repair

  9. Have you ever considered about adding a little bit more than just your articles?
    I mean, what you say is important and everything. However just imagine if you added some great graphics
    or video clips to give your posts more, “pop”!

    Your content is excellent but with images and videos, this blog could definitely be
    one of the greatest in its niche. Fantastic blog!

  10. платная наркологическая скорая помощь http://skoraya-narkologicheskaya-pomoshch-moskva12.ru/ .

  11. Bet303.com is operated by Codex B.V., a company incorporated under the laws of Curaçao with
    Company Number 160873 and has a valid Certificate of Operation. This Certificate of Operation is
    subject to the National Ordinance on Off shore Games of Hazard.

  12. There are various tools and websites that claim to allow users to view private Instagram profiles,
    but it’s important to gain access to these like 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 habit to view a private profile is to send a follow demand directly to the user.
    Always prioritize privacy and admiration in your online interactions.

    Here is my webpage :: private instagram viewer free

  13. нарколог на дом вывод из запоя химки нарколог на дом вывод из запоя химки .

  14. вывод из запоя на дому в химкие вывод из запоя на дому в химкие .

  15. The 10 Most Dismal Asbestos Attorney Mesothelioma Fails Of All Time Could Have
    Been Prevented mesothelioma lawyer

  16. Data HK 6D表示:

    I’m not sure why but this site is loading incredibly slow for me.
    Is anyone else having this problem or is it a issue on my end?
    I’ll check back later on and see if the problem still exists.

    https://stedwardgg.com/

  17. Diplomi_pjma表示:

    купить диплом образования екатеринбурга landik-diploms.ru .

  18. Responsible For The 3 Wheel Buggy Budget?
    10 Very Bad Ways To Invest Your Money Small 3 Wheel Stroller

  19. It’s The Ugly The Truth About Remote Key Repair car remote key repair [https://images.google.be]

  20. Why People Don’t Care About Accident Lawyer Philadelphia Accident Attorney

  21. RileyBok表示:

    Viagra * Cialis * Levitra

    All the products you are looking suitable are currently available for 1+1.

    4 more tablets of an individual of the following services: Viagra * Cialis * Levitra

    https://pxman.net

  22. Hi there! This article couldn’t be written much better!
    Reading through this article reminds me of my previous
    roommate! He continually kept talking about this.

    I will forward this article to him. Pretty sure he’ll have a very good read.
    Thank you for sharing!

  23. Guide To Buying Mobility Scooter: The Intermediate Guide In Buying Mobility Scooter buying mobility Scooter (https://Te.legra.ph/)

  24. It’s The Complete Cheat Sheet On Hyundai Tucson Key Replacement Hyundai elantra key replacement

  25. Hi there, just wanted to tell you, I liked this blog post.
    It was funny. Keep on posting!

  26. 10 Of The Top Mobile Apps To Use For Mesothelioma
    Asbestos Claims mesothelioma lawyer

發佈留言

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