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,233,586 Responses

  1. Tyler表示:

    I love your blog.. very nice colors & theme. Did you design this website yourself
    or did you hire someone to do it for you? Plz answer back as I’m looking to
    construct my own blog and would like to find out
    where u got this from. appreciate it

  2. bisma777表示:

    This is a great tip particularly to those fresh to the blogosphere.
    Short but very accurate info… Many thanks for sharing this one.

    A must read post!

  3. Anderson表示:

    You really make it seem really easy with your presentation however I
    find this topic to be actually something which I believe I would by no means understand.

    It sort of feels too complex and very extensive for me.
    I am taking a look forward for your subsequent put up,
    I’ll try to get the grasp of it!

  4. Wow, awesome blog structure! How long have you been running a blog for?
    you make blogging look easy. The overall look of your web site is magnificent, as smartly as the content!

  5. ev taşıma表示:

    Ev Taşıma | Taşınma sürecinde karşılaşılabilecek sorunlar ve çözümleri üzerine yazılmış bu makale çok bilgilendirici. Kozcuoğlu Ev Taşıma olarak, olası sorunları önceden önlemek için gerekli tüm tedbirleri alıyoruz.

  6. I am regular visitor, how are you everybody? This article posted
    at this website is in fact fastidious.

  7. ufabet表示:

    I am extremely impressed together with your writing talents and also with the layout on your weblog.
    Is that this a paid subject or did you modify it your self?
    Anyway stay up the excellent quality writing, it’s rare to look a great blog like this one today..

    Also visit my page :: ufabet

  8. 사설토토表示:

    hi!! Exceptionally fascinating discourse happy that I went over such educational post. Keep doing awesome. Happy to be a piece of your net group. https://codehillacademy.com

  9. KevinSounc表示:

    http://sweetbonanza.network/# sweet bonanza nas?l oynan?r

  10. These are truly fantastic ideas in regarding blogging.
    You have touched some nice points here. Any way keep up wrinting.

  11. Kevin表示:

    Fantastic goods from you, man. I have understand your stuff previous to and you
    are just extremely excellent. I really like what you have acquired here, certainly like what you’re saying and the way in which you say it.
    You make it enjoyable and you still care for to
    keep it smart. I can not wait to read much more from you.
    This is really a wonderful website.

  12. KevinSounc表示:

    http://sweetbonanza.network/# sweet bonanza 100 tl

  13. This is my first time go to see at here and i am truly
    impressed to read all at one place.

  14. Kennethmab表示:

    Официальный клуб Sukaaa предлагает новым игрокам бонус 325% в 4 этапа, за активное повышение статуса – игрок получает круглосуточную поддержку и участие в турнирах. Новых игроков привлекает не только бонус бездеп за регистрацию, но и дизайн https://t.me/s/sykaaa_official_casino на сайте наглядное меню, которое позволяет в пару кликов найти нужный провайдер, выбрать игру или сделать депозит.

  15. Matthias表示:

    Hello to all, as I am really keen of reading this web site’s
    post to be updated regularly. It contains nice stuff.

  16. KevinSounc表示:

    https://slotsiteleri.bid/# slot oyun siteleri

  17. I really like your blog.. very nice colors & theme. Did you make this website yourself or did you hire
    someone to do it for you? Plz respond as I’m looking to construct my own blog and would like to find out where u got this from.

    thank you

  18. PokemonToto表示:

    Veryy great post. Ӏ simply stumbled upon your blog ɑnd wished to mention thɑt Ӏ’ve trսly enjoyed
    suffing аround your blog posts. Ꭺfter all I will bee subscribing fоr yoᥙr feed and Ӏ
    hope you ԝrite once mߋre soon!

    Here is my web blog PokemonToto

  19. 14 Misconceptions Common To Volvo V40 Key volvo S60 key replacement

  20. jilislot表示:

    Hey very nice blog!

  21. KevinSounc表示:

    http://sweetbonanza.network/# sweet bonanza yorumlar

  22. Remarkable things here. I’m very satisfied to peer your post.
    Thanks so much and I’m looking forward to contact you.

    Will you kindly drop me a e-mail?

    my webpage :: wholesale bath bombs

  23. mega888表示:

    It’s impressive that you are getting thoughts from this paragraph as well as from our dialogue made at
    this place.

  24. fantastic points altogether, you simply won a brand new reader.
    What could you recommend about your post that you made a few days in the past?
    Any sure?

    My website 商業登記證費用

  25. This is really interesting, You are a very skilled blogger.
    I’ve joined your rss feed and look forward how to eat healthy seeking
    more of your great post. Also, I’ve shared your site in my social networks!

  26. Very good blog! Do you have any tips for aspiring writers?
    I’m planning to start my own website soon but I’m a little lost
    on everything. Would you propose starting with a free platform like
    Wordpress or go for a paid option? There are
    so many options out there that I’m completely overwhelmed ..
    Any tips? Appreciate it!

  27. Darrelherse表示:

    deneme veren slot siteleri: canl? slot siteleri – oyun siteleri slot

  28. Ev Taşıma | Müşteri memnuniyetinin ev taşıma sektöründe ne kadar önemli olduğunu bu makalede çok iyi anlatmışsınız. Kozcuoğlu Ev Taşıma olarak, memnuniyeti her zaman en üst düzeyde tutmak için çalışıyoruz.

發佈留言

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