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,372,123 Responses

  1. Lizzie Harmon表示:

    Is there anything better than leaving a barber shop looking sharp? Just had mine done today—check it out at barber shop θεσσαλονικη

  2. DanielAbice表示:

    http://cipharmdelivery.com/# cipro 500mg best prices

  3. See What Gas Safety Inspection Milton Keynes Tricks The Celebs Are Using gas safety inspection milton keynes (Humanlove.stream)

  4. Hello, always i used to check website posts
    here in the early hours in the morning, as i love to find
    out more and more.

  5. вывод из запоя краснодар наркология вывод из запоя краснодар наркология .

  6. SamuelBix表示:

    cipro: CiPharmDelivery – ciprofloxacin order online

  7. Jessetor表示:

    Получайте кэшбэк до 5% на каждый покупку с картой Сбербанка! Экономьте на покупках в магазинах, кафе и онлайн. Простое оформление и удобное управление через мобильное приложение.
    Начните экономить уже сегодня!======>
    Промсвязьбанк – Потребительский кредит в Кисловодске

  8. Dive into the exciting world of online gaming with kiss918, offering a wide selection of casino games and big winning opportunities.

  9. The Most Powerful Sources Of Inspiration Of Mazda Key Fob
    Replacement mazda spare key replacement

  10. Thank you a bunch for sharing this with all people you actually realize what you are talking about!
    Bookmarked. Kindly also talk over with my
    site =). We could have a link change contract between us

    Here is my web blog: senior retirement communities

  11. Lloyd Collins表示:

    Trusting my case with an experienced ###ANYKEYWORD### gave me peace of mind during such stressful vehicle collision lawyer

  12. Hello friends, how is everything, and what you want
    to say regarding this post, in my view its genuinely amazing designed for me.

    Check out my web blog pro nerve 6 reviews

  13. DanielAbice表示:

    http://prednibest.com/# 40 mg prednisone pill

  14. EdgarWat表示:

    Интересные статьи о займах – https://rus-linux.net/press-reliz/2021-12/sravni.html

  15. SamuelBix表示:

    how to buy clomid without prescription: can i get clomid pill – how can i get clomid

  16. SamuelBix表示:

    prednisone 20mg for sale: PredniBest – prednisone online sale

  17. RobertJar表示:

    where to buy generic clomid no prescription: how can i get generic clomid price – cost of clomid

  18. Elva Fuller表示:

    Appreciate the insightful article. Find more at Helpful resources

  19. Apreciez foarte mult atenția la detalii pe care o oferă serviciile funerare din Timișoara! servicii funerare servicii funerare timisoara

  20. Nikefut表示:

    dark web site darkmarkets darknet websites

  21. DanielAbice表示:

    http://prednibest.com/# average cost of prednisone

  22. Odellces表示:

    Scuba diving lovers are drawn in order to the thrill regarding exploring underwater realms, making scuba diving-themed gifts an innovative choice. Whether to get a seasoned diver or perhaps a curious beginner, these kinds of gifts cater to both practical and even sentimental needs, blending functionality with some sort of deep appreciation regarding the ocean.

    Sensible items like high-quality dive watches, wetsuit accessories, or small underwater cameras could enhance a diver’s experience. These presents are useful although also celebrate the diver’s connection to the particular ocean.

    https://urbanmatter.com/gifts-as-deep-as-the-ocean-exploring-the-world-of-scuba-diving-themed-presents/

    For an extra personal touch, take into account dive-inspired art, precious jewelry, or custom equipment. These pieces record the essence in the underwater realm, providing divers a method to showcase their passion even though on dry land.

  23. Why SEO Software For Small Business Is Still Relevant In 2023 Seo software download

  24. SamuelBix表示:

    buy cipro online usa: ciprofloxacin mail online – buy ciprofloxacin

  25. The future belongs to those who can think critically, adapt quickly, and solve complex problems Ρομποτική για παιδιά

  26. Предлагаем услуги профессиональных инженеров офицальной мастерской.
    Еслли вы искали ремонт стиральных машин smeg в москве, можете посмотреть на сайте: ремонт стиральных машин smeg рядом
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

發佈留言

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