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,368,100 Responses

  1. Charlesrab表示:

    Pharmacie sans ordonnance Medicaments en ligne livres en 24h Pharmacie sans ordonnance

  2. 4.4. потребителю нельзя создавать более одной учетке
    на домашнее хозяйство, https://playpokerruking.ru/ ай-пи адрес и/или
    ноут.

  3. Excellent write-up. I certainly love this website.
    Continue the good work!

  4. JamesBuice表示:

    mexican mail order pharmacies: mexican pharmacy – mexican drugstore online
    mexican drugstore online

  5. JamesBuice表示:

    purple pharmacy mexico price list: purple pharmacy mexico price list – mexican drugstore online
    reputable mexican pharmacies online

  6. HeathZex表示:

    Viagra pas cher paris: Sildenafil Viagra – Viagra pas cher livraison rapide france

  7. Charlesrab表示:

    pharmacie en ligne sans ordonnance cialis generique pharmacie en ligne france pas cher

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

  9. EU303表示:

    Wow, awesome weblog layout! How lengthy have you ever been running
    a blog for? you make running a blog glance easy.

    The whole glance of your site is magnificent, as smartly as the content material!

    Here is my webpage

  10. Charlesrab表示:

    pharmacie en ligne france pas cher Cialis generique prix pharmacie en ligne france pas cher

  11. Велосипеды velosiped-magazin.ru

    Если Вы планировали найти доставка велосипедов по москве в Москве, то звоните прямо сейчас. Наш контактный телефон +7(495)128-48-26 для связи и получения консультации. Наши менеджеры помогут с выбором и оформят Вам заказ с доставкой по Московской области.

  12. Hello just wanted to give you a quick heads up and let you know a few of the images aren’t loading
    properly. I’m not sure why but I think its a linking issue.
    I’ve tried it in two different internet browsers and both show the same outcome.

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

  14. HeathZex表示:

    acheter mГ©dicament en ligne sans ordonnance: pharmacie en ligne sans ordonnance – pharmacie en ligne avec ordonnance

  15. Nice answers in return of this difficulty with genuine arguments and explaining the
    whole thing regarding that.

  16. HeathZex表示:

    pharmacies en ligne certifiГ©es: pharmacie en ligne – Pharmacie sans ordonnance

  17. JamesBuice表示:

    buying prescription drugs in mexico: mexican pharmacy – mexico drug stores pharmacies
    mexico drug stores pharmacies

  18. Stephengen表示:

    http://clssansordonnance.icu/# Pharmacie sans ordonnance

  19. More Info表示:

    My brother suggested I may like this website. He was entirely right.
    This post truly made my day. You can not consider simply how so much time I had spent for this information! Thanks!

  20. Stephengen表示:

    https://clssansordonnance.icu/# Achat mГ©dicament en ligne fiable

  21. See What Drive Autofold Mobility Scooter Tricks The Celebs Are Using autofold Mobility Scooter

  22. 10 Things We Hate About Replacement Sealed Double
    Glazed Units door seal Repair near Me

  23. What i do not understood is in reality how you are now not actually a lot
    more smartly-liked than you may be now. You are so intelligent.
    You know thus considerably when it comes to this topic, produced me
    in my view believe it from a lot of varied angles. Its like men and women aren’t interested except
    it is something to accomplish with Girl gaga!

    Your own stuffs great. At all times maintain it up!

  24. Руслан Исаков считается признанным экспертом в области
    https://otvet.mail.ru/question/230991583 и бк, а также талантливым
    автором текстов. 1.

  25. Hello, I enjoy reading all of your article.

    I wanted to write a little comment to support you.

    Here is my web blog :: คอร์สเรียนดำน้ำ

  26. HeathZex表示:

    SildГ©nafil 100 mg prix en pharmacie en France: Sildenafil Viagra – Viagra 100 mg sans ordonnance

  27. Stephengen表示:

    http://vgrsansordonnance.com/# Viagra homme sans ordonnance belgique

  28. Charlesrab表示:

    pharmacie en ligne sans ordonnance cialis prix pharmacie en ligne fiable

  29. We are a group of volunteers and opening a new scheme in our
    community. Your website provided us with valuable info to work on. You have done an impressive job and our whole community will be thankful to you.

發佈留言

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