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,231,541 Responses

  1. Hi there! I’m at work surfing around your blog from my
    new iphone 4! Just wanted to say I love reading your blog and look forward to all
    your posts! Keep up the excellent work!

  2. PokemonToto表示:

    Hi theгe, i гead your blog from time to timе аnd i owwn ɑ
    similaг one and i was just wondering іf yoս get а lot օf spsm responses?
    If sso һow ԁo yoᥙ protect aɡainst іt, any plugin οr anythіng you can recommend?
    Ι get so much lately it’s driving mе insane soo
    any support iis ѵery mսch appreciated.

    Μy hοmepage – PokemonToto

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

  4. Very descriptive article, I liked that bit.
    Will there be a part 2?

  5. Darrelherse表示:

    slot siteleri bonus veren: slot casino siteleri – en guvenilir slot siteleri

  6. Fantastic goods from you, man. I have understand your stuff previous to and you’re just too excellent.
    I actually like what you’ve acquired here, really 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 smart.
    I can not wait to read much more from you. This is really a great
    web site.

  7. Darrelherse表示:

    casino slot siteleri: en yeni slot siteleri – en iyi slot siteler

  8. Darrelherse表示:

    slot siteleri 2024: oyun siteleri slot – canl? slot siteleri

  9. Simply want to say your article is as amazing.

    The clarity in your post is simply cool and i can assume you are
    an expert on this subject. Well with your
    permission allow me to grab your RSS feed
    to keep up to date with forthcoming post.
    Thanks a million and please keep up the enjoyable work.

  10. Darrelherse表示:

    en cok kazandiran slot siteleri: slot oyunlar? siteleri – guvenilir slot siteleri 2024

  11. Darrelherse表示:

    yeni slot siteleri: deneme veren slot siteleri – en iyi slot siteleri 2024

  12. KevinSounc表示:

    https://sweetbonanza.network/# sweet bonanza yasal site

  13. Darrelherse表示:

    en iyi slot siteler: en iyi slot siteleri – en iyi slot siteler

  14. wd808表示:

    Want to know more about where to find the best online casino games?
    There are some hot spots for big wins, and wd808 stands out as one of the top online casinos at the moment.

  15. wd808win表示:

    Aw, this was an extremely nice post. Finding the time and actual
    effort to create a really good article… but what can I say… I put things
    off a lot and never manage to get nearly anything done.

  16. Hello! I’ve been following your website for some time now and finally got
    the bravery to go ahead and give you a shout out from
    Atascocita Tx! Just wanted to mention keep up the
    good work!

  17. Hey There. I found your weblog the use of msn.
    That is an extremely well written article. I will make sure to bookmark it and return to read extra of your helpful information.
    Thanks for the post. I’ll definitely comeback.

  18. wd808win表示:

    Bermain judi online sekarang lebih mudah dari sebelumnya!
    Coba di situs teratas seperti wd808 Slot.

  19. MatthewChils表示:

    VAVADA is an Online Gaming Project with transparent payouts. Welcome to official VAVADA channel! We strive to give a high-quality experience to our players скачать официальный вавада

  20. Richardver表示:

    Наши инженеры качественно и с гарантией выполнят все необходимые диагностические и ремонтные работы для восстановления вашей техники. Запишитесь на ремонт прямо сейчас https://bluesteel.tv/2020/05/25/hello-world/#comment-7145

  21. wd808win表示:

    If you’re wondering about the best online casino games, look
    no further. You can play and win big at several popular sites, including
    wd808, which is currently one of the best online casinos available

  22. dadyar表示:

    Thanks , I’ve recently been searching for info
    approximately this topic for ages and yours is the best I’ve came upon so far.
    However, what about the bottom line? Are you sure concerning the source?

  23. 10 Websites To Aid You To Become An Expert In Citroen Berlingo Van Key Replacement citroen nemo key replacement

  24. Thanks for every other informative web site. Where else could I get that kind of info written in such
    an ideal way? I’ve a mission that I’m just now working on, and I’ve
    been on the glance out for such information.

  25. index表示:

    What’s Happening i am new to this, I stumbled upon this I have found It absolutely useful and it has aided
    me out loads. I’m hoping to give a contribution & aid different customers like
    its helped me. Good job.

  26. Darrelherse表示:

    deneme bonusu veren siteler: slot siteleri bonus veren – en iyi slot siteleri 2024

發佈留言

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