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,466,614 Responses

  1. JacobLoody表示:

    кухни под заказ екатеринбург — Эксклюзивные решения для кухонь под заказ в Екатеринбурге от arch-mag.

  2. Richard Lane表示:

    This was quite helpful. For more, visit queen and slim

  3. kraken 14at表示:

    Right here is the perfect website for everyone who wishes
    to find out about this topic. You understand a whole lot its almost hard to argue with you (not that I personally would want to…HaHa).
    You definitely put a new spin on a subject that’s been discussed for decades.
    Wonderful stuff, just wonderful!

  4. Leona Hayes表示:

    Thanks for the great content. More at roofing companies near me

  5. Hattie Weber表示:

    This was highly educational. More at عمل پی ار کی

  6. Why We Why We Maryland Birth Injury Attorneys (And You Should Too!) injury claim lawyer

  7. Appreciate the recommendation. Let me try it out.

  8. A Journey Back In Time What People Talked About Mystery Box 20 Years Ago Best Gaming Mystery Box

  9. JasonUnsoG表示:

    https://denemebonusuverensiteler25.com/# deneme bonusu veren siteler

  10. I appreciate the article, but I respectfully disagree with some points.

  11. Shaneevige表示:

    Please let me know if you’re looking for a article writer for your blog. You have some really great posts and I believe I would be a good asset. If you ever want to take some of the load off, I’d really like to write some material for your blog in exchange for a link back to mine. Please send me an e-mail if interested. Thanks!
    https://millionigrushek.ru/

  12. Hope表示:

    I am actually grateful to the holder of this website who has shared this wonderful piece of
    writing at at this place.

  13. JasonUnsoG表示:

    http://slotsiteleri25.com/# guvenilir slot siteleri

  14. Jackie表示:

    There is definately a lot to know about this issue.
    I like all of the points you’ve made.

  15. Steve Roberts表示:

    Great job! Discover more at website design

  16. 안양 유흥가쪽 경기 안 타는 유일한 가게 저희 안양 노래방알바에서 고민없이 돈 버세요

  17. Acheter Viagra Pfizer Belgique, Pharmacie En Ligne. Acheter viagra en ligne, meilleur viagra en ligne, Psmodcom. Viagra en ligne, viagra vente libre, Dwdt Magasin en ligne de pilule. Levitra prix pharmacie avoir du sans ordonnance comment acheter authentique. Canada, en ligne sildenafil obtenez sans pharmacie, LInde, le prix achat en. https://medicamentvente.space/cepazine/ Generique Cepazine Vente

  18. Loving the info shared about these native salons! Your hobby for aiding others to find hair companies in West Vancouver shines because of—thanks to come back! Don’t forget to review out my web site at hair salon

  19. Wallacefex表示:

    deneme bonusu veren yeni siteler: yat?r?ms?z deneme bonusu veren siteler – yat?r?ms?z deneme bonusu veren siteler

  20. Carmen表示:

    Hey this is kinda of off topic but I was wondering if blogs use WYSIWYG editors or if
    you have to manually code with HTML. I’m starting a blog soon but have no coding
    skills so I wanted to get guidance from someone with experience.
    Any help would be greatly appreciated!

  21. Thanks for the informative post. More at sod service

  22. FobertWen表示:

    I got this website from my friend who told me on the topic of this web page and now this time I am browsing this site and reading very informative articles or reviews at this place.
    https://millionigrushek.ru/

  23. Rosa Mann表示:

    Appreciate the thorough insights. For more, visit pool resurfacing service

  24. Despomymn表示:

    На официальном сайте букмекерской конторы [url=https://mostbet-wnz1.xyz/]мостбет[/url] вы найдете актуальные коэффициенты на спортивные события, выгодные акции и бонусы для игроков, удобный интерфейс и безопасные условия для ставок.

  25. Marcelino表示:

    It’s actually very complicated in this full of activity life to listen news on TV, so I only use world wide web for that purpose, and
    take the newest information.

  26. Torsten表示:

    Thanks for some other excellent post. Where else may just anybody get that type of information in such an ideal means of writing?
    I have a presentation next week, and I am on the search
    for such info.

  27. Gambling Recommendations For Major Casino Games 에볼루션 토토

  28. FrankEmine表示:

    canl? casino siteleri: guvenilir casino siteleri – deneme bonusu veren casino siteleri

  29. Wallacefex表示:

    deneme bonusu veren yeni siteler: deneme bonusu veren yeni siteler – yat?r?ms?z deneme bonusu veren siteler

發佈留言

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