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,374,084 Responses

  1. 비아 몰表示:

    Hello there, just became aware of your blog through Google, and found that it’s really informative.
    I am gonna watch out for brussels. I will appreciate if you continue this in future.
    A lot of people will be benefited from your writing.
    Cheers!

  2. Near Me表示:

    Porsche Panamera Key: What’s No One Is Talking About Near Me

  3. Jeremypag表示:

    semaglutide online semaglutide tablets buy semaglutide pills

  4. Jeremypag表示:

    ozempic online ozempic generic buy ozempic

  5. Inviertas表示:

    Hi, after reading this remarkable piece of writing i am too happy to share my experience here with mates.

    Take a look at my web site; Inviertas

  6. HaroldBig表示:

    semaglutide tablets: semaglutide online – rybelsus pill

  7. BarryDof表示:

    https://ozempic.art/# ozempic coupon

  8. Профессиональный сервисный центр по ремонту сигвеев в Москве.
    Мы предлагаем: сигвей ремонт аккумулятора
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  9. RamonRek表示:

    ozempic online: ozempic – Ozempic without insurance

  10. A Complete Guide To Upvc Windows And Doors Near Me Dos And Don’ts upvc windows Near me

  11. RamonRek表示:

    semaglutide online: buy semaglutide pills – rybelsus coupon

  12. For all these factors, the off-label or nonprescription use of
    GHS peptides in bodybuilders is not recommended.

  13. Muscle Growth表示:

    Substances have been established that simulate the
    stimulatory activities of GHRP on GH launch
    in animals and male (12, 13).

  14. Jeremypag表示:

    ozempic online buy ozempic pills online buy cheap ozempic

  15. HaroldBig表示:

    ozempic online: buy cheap ozempic – ozempic online

  16. Hi there! I just wanted to ask if you ever have any problems
    with hackers? My last blog (wordpress) was hacked and I
    ended up losing several weeks of hard work due
    to no backup. Do you have any methods to protect against hackers?

  17. pafipakam.org表示:

    Hey there! Quick question that’s totally off topic. Do you
    know how to make your site mobile friendly? My web site looks weird when viewing
    from my iphone. I’m trying to find a theme or plugin that might be able to resolve this problem.
    If you have any suggestions, please share. Many thanks!

  18. HaroldBig表示:

    buy ozempic pills online: Ozempic without insurance – buy ozempic

  19. BarryDof表示:

    https://ozempic.art/# buy cheap ozempic

  20. Lastly, it’s not uncommon for individuals to have some shortages or blindspots in their
    partnership skills.

  21. Marylyn表示:

    Beware Of These “Trends” About 1kg Coffee Beans
    1kg coffee beans price uk – Marylyn

  22. HaroldBig表示:

    buy ozempic pills online: ozempic – ozempic cost

  23. Jeremypag表示:

    semaglutide tablets buy semaglutide online semaglutide online

  24. I’m not sure exactly why but this web 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 and see if the problem still exists.

    Feel free to visit my web-site; famous catering KL

  25. Florentina表示:

    The subtunical plexi branch right into emissary veins which pass through the
    tunica albuginea [Keegan and Penson, 2013]

  26. Jeremypag表示:

    semaglutide online semaglutide cost buy semaglutide online

  27. HaroldBig表示:

    ozempic online: buy ozempic – ozempic coupon

  28. Профессиональный сервисный центр по ремонту сетевых хранилищ в Москве.
    Мы предлагаем: ремонт сетевого хранилища
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  29. اویل کش表示:

    اویل کش (Oil Catch Can) یک قطعه مهم در سیستم‌های موتور است که به منظور جلوگیری از ورود بخارات روغن
    و گازهای غیرسوختی به سیستم
    ورودی هوا و محفظه احتراق طراحی شده
    است. این دستگاه به‌خصوص در خودروهای با موتورهای قدرتمند، تقویت‌شده و مسابقه‌ای مورد استفاده قرار می‌گیرد.
    در ادامه به بررسی جزئیات کامل اویل کش، نحوه عملکرد، مزایا، معایب
    و کاربردهای آن خواهیم پرداخت.

    نوربرت پرفورمنس

發佈留言

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