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,230,420 Responses

  1. HassanbuifS表示:

    https://denemebonusuverensiteler.top/# deneme bonusu veren siteler yerliarama.org
    deneme bonusu veren siteler betturkey betturkey.com

  2. DavidLic表示:

    Бесплатные виртуальные номера страны Белоруссия с кодом +375 для приема СМС, получения активации сервисов и аренды мобильного телефона купить американский номер

  3. Тут можно преобрести оружейные сейфы сейф сейфы оружейный оружие

  4. HassanbuifS表示:

    https://casinositeleri.win/# Canl? Casino Siteleri
    deneme bonusu veren siteler betturkey

  5. Jesus表示:

    New Yorkers who suffer mesothelioma should receive
    the most compensation possible. asbestos claim (Jesus) lawyers who have experience, like the ones
    at Lipsitz Green Scime Cambria can assist.

  6. ScottAtora表示:

    В настоящее время одной из ключевых современных информационных угроз для общества в сфере медиабезопасности становится вовлечение детей и подростков в деструктивные Интернет-сообщества настоящий слив школьниц

  7. 9 . What Your Parents Teach You About How To Get Assessed For ADHD As An Adult How To Get Assessed For Adhd As An Adult

  8. Тут можно преобрести оружейный шкаф купить в москве оружейный шкаф цена

  9. Тут можно преобрести оружейные сейфы в москве сейф для охотничьего ружья цена

  10. Hi there! This is kind of off topic but I need some
    help from an established blog. Is it hard to set up your own blog?
    I’m not very techincal but I can figure things out pretty fast.
    I’m thinking about setting up my own but I’m not sure where to start.

    Do you have any points or suggestions? Appreciate it

  11. Nereida表示:

    You’ll Be Unable To Guess Composite Door Crack Repair’s Tricks composite door crack repair – Nereida

  12. Тут можно преобрести сейф для карабина шкафы для оружия

  13. Nikefut表示:

    darknet links dark web markets dark web search engines

  14. Right now it looks like WordPress is the top blogging platform out there right now.
    (from what I’ve read) Is that what you’re using on your blog?

    https://ww1.datasgp.work/

  15. It is perfect time to make some plans for the future
    and it’s time to be happy. I have read this post and if I could I desire to suggest you few interesting
    things or suggestions. Maybe you can write next articles referring to this article.
    I wish to read even more things about it!

    https://w8.angkakeramat.buzz/

  16. The Top Reasons People Succeed In The Beer Wine Refrigerator Industry small wine chiller Fridge

  17. 7 Small Changes You Can Make That’ll Make A Big Difference In Your
    Sports Toto Results 메이저사이트

  18. Jestine表示:

    The Three Greatest Moments In Upvc Windows Repair History
    upvc window repairs near me (Jestine)

  19. Five Essential Qualities Customers Are Searching For In Every Fireplace
    electric Firesuite

  20. I don’t know whether it’s just me or if perhaps everyone else encountering problems with
    your site. It seems like some of the written text in your content
    are running off the screen. Can somebody else please comment and let me know if this is happening to
    them too? This may be a issue with my internet browser because I’ve had this happen previously.

    Cheers

    Feel free to surf to my page – Bang King 30000

  21. LarryCoell表示:

    matadorbet giris matadorbet bid matadorbet bid

  22. I was more than happy to discover this web site. I wanted to thank you for your time for this particularly wonderful read!!

    I definitely loved every little bit of it and I have you bookmarked to look at new information on your site.

  23. Howdy would you mind letting me know which web host you’re working with?
    I’ve loaded your blog in 3 completely different browsers and
    I must say this blog loads a lot quicker then most. Can you recommend a good internet hosting provider at a reasonable price?
    Many thanks, I appreciate it!

  24. ClydePab表示:

    slot oyunlar? puf noktalar?: az parayla cok kazandiran slot oyunlar? – en kazancl? slot oyunlar?

  25. LarryCoell表示:

    deneme bonusu veren siteler deneme bonusu veren siteler betturkey betturkey.com deneme bonusu veren siteler denemebonusu2026.com

  26. Brandon表示:

    10 Startups Set To Change The Citroen Key Industry For The
    Better citroen nemo key fob programming (Brandon)

  27. Тут можно преобрести сколько стоит сейф для ружья оружейные шкафы и сейфы

發佈留言

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