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,479,130 Responses

  1. The 12 Best Bifold Door Repair Accounts To Follow On Twitter repairing Bifold doors

  2. Roland Law表示:

    A Trip Back In Time How People Discussed Upvc Door Hinge 20 Years Ago cost Of replacing window Hinges

  3. The No. Question That Everyone In Locksmith Cars Should Be Able Answer locksmith Car Keys (https://osman-crabtree.thoughtlanes.net)

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

  5. Fantastic forum posts, Thanks!

  6. AgustinBougs表示:

    https://indianpharmdelivery.com/# best india pharmacy
    best india pharmacy

  7. Toto4D表示:

    20 Trailblazers Lead The Way In Togel4d Toto4D

  8. It’s the best time to make some plans for the future and it
    is time to be happy. I have read this post and
    if I could I desire to suggest you some interesting things or tips.

    Maybe you could write next articles referring
    to this article. I want to read even more
    things about it!

  9. The 3 Greatest Moments In Metal Triple Bunk Bed History double Bed and single bunk bed

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

  11. How To Get More Benefits Out Of Your Bmw Replacement Key Fob Replacement bmw key

  12. Свежие события появляются в рекламной ленте на главной странице сайта и в приложениях.

  13. Профессиональный сервисный центр ремонт телефонов на дому ремонт мобильных телефонов

  14. This Is How Togel Resmi Indonesia Will Look Like In 10 Years Situs toto Togel

  15. AgustinBougs表示:

    http://drugs24.pro/# erection pills
    top 10 online pharmacy in india

  16. Awinitadox表示:

    You suggested this exceptionally well.
    caesars casino online promo code no deposit casino bonus canada internet casino game online

  17. Why Program Keys For Cars Is Still Relevant In 2023 Reprogramming car Key

  18. Kory Leal表示:

    The 10 Scariest Things About Patio Doors Repairs patio doors repair – Alonzo

  19. Why Is Adults Toy For Men So Popular? adult Couples toys

  20. You’ll Never Guess This Walking Pad Under Desk’s Tricks walking pad under desk (Christin)

  21. Greetings from Colorado! I’m bored at work so I decided to check out
    your site on my iphone during lunch break. I love the information you provide here and can’t wait to take a look when I get home.
    I’m surprised at how fast your blog loaded on my phone
    .. I’m not even using WIFI, just 3G .. Anyways,
    superb blog!

  22. BrandonJer表示:

    п»їlegitimate online pharmacies india india pharmacy indian pharmacy paypal

  23. Fantastic goods from you, man. I have understand your stuff
    previous to and you’re just too magnificent. I really like what
    you’ve acquired here, certainly like what you’re saying and the way in which you say it.
    You make it entertaining and you still take care
    of to keep it sensible. I can’t wait to read far more from you.

    This is actually a tremendous web site.

  24. Hello it’s me, I am also visiting this web site on a regular
    basis, this website is genuinely good and the viewers are really sharing fastidious thoughts.

  25. Sazrcsd表示:

    Как правильно купить диплом колледжа и пту в России, подводные камни
    5gruppa365-diploms.ru

  26. Five Case Battle Lessons From The Professionals case Battle Cs2

  27. RichardKnore表示:

    DANKBROS LTD – Free company information from Companies House including registered office address, filing history, accounts, annual return, officers http://jack-hughes.com/?URL=https://dankbros.net/

  28. Shannon Binns表示:

    Five Killer Quora Answers On Electric Fire Wall Mounted electric fire wall mount

  29. Quality articles is the secret to interest the users to visit the web site, that’s what this site is providing.

發佈留言

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