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,458,390 Responses

  1. Html5 Poker表示:

    Look at my blog … Html5 Poker

  2. AmandaAscem表示:

    Discover the world of comfort with our pools!
    We offer a huge selection of pools, their installation and maintenance.
    More detailed information on the link фильтр для бассейна крипсол
    Create an oasis at home with best solutions.
    Individual approach and guarantees for all work.

  3. Brandonnot表示:

    canadian pharmacy: Canadian Md Pharm – the canadian drugstore

  4. AmandaAscem表示:

    Discover the world of enjoyment with our pools!
    We offer a widest selection of pools, their installation and maintenance.
    More detailed information on the link цеолит купить в тюмени
    Create an oasis at home with high-quality solutions.
    Professional installation and guarantees for all work.

  5. CurtisBam表示:

    Indian Cert Pharm: Online medicine – Indian Cert Pharm

  6. Hmm is anyone else experiencing problems with the pictures on this blog loading?
    I’m trying to determine if its a problem on my end
    or if it’s the blog. Any suggestions would be greatly appreciated.

  7. What’s up friends, fastidious article and nice arguments commented at
    this place, I am in fact enjoying by these.

  8. Brandonnot表示:

    Mexican Easy Pharm: Mexican Easy Pharm – Mexican Easy Pharm

  9. AmandaAscem表示:

    Discover the world of enjoyment with our pools!
    We offer a huge selection of pools, their installation and maintenance.
    More detailed information on the link цеолит для фильтра
    Create an oasis at home with best solutions.
    Individual approach and guarantees for all work.

  10. JefferySow表示:

    Сайт новостей о шоу-бизнесе. Публикации о кинопремьерах, музыкальных новинках, событиях на телевидении и жизни знаменитостей. Обзоры фильмов и сериалов, рецензии на альбомы, интервью с представителями индустрии развлечений. Регулярное обновление новостной ленты. Информация о скандалах, светских мероприятиях и других событиях в мире шоу-бизнеса. Аналитика и комментарии по актуальным темам.
    концерт N1 Media

  11. FemeFun表示:

    I need to to thank you for this excellent read!!
    I certainly loved every bit of it. I have you saved as a favorite to look at new things you post…

  12. Iyannaobesk表示:

    дмитрий лесной обучение покеру
    дмитрий лесной покер школа

  13. What’s up to all, the contents existing at this web site are truly awesome for people knowledge,
    well, keep up the good work fellows.

  14. Ahaa, its nice dialogue regarding this piece of writing at this place at this website, I have read
    all that, so at this time me also commenting here.

  15. kudustoto表示:

    situs terbaik cuma ada di situs kudustoto

  16. PokerTube表示:

    Here is my site: PokerTube

  17. Antoniofep表示:

    Betzula, canl? bahis konusunda benzersiz secenekler sunar. en heyecanl? maclar icin Betzula giris yaparak yuksek oranlar? kesfedebilirsiniz.

    Betzula’n?n guvenilir altyap?s?, kullan?c?lar?na her zaman kolayl?k saglar. Betzula Twitter hesab?n? takip ederek en son haberlerden haberdar olabilirsiniz.

    favori futbol kuluplerinizin bahislerinizi an?nda yapabilirsiniz.

    Ayr?ca, platformun en yeni versiyonu, kullan?c?lara s?n?rs?z erisim sunar. Ozel olarak, betzula, profesyonel bir deneyim saglar.

    Betzula, en genis bahis seceneklerinden ozel turnuvalara kadar en iyi deneyimi yasatmay? amaclar. en guncel oranlar? gormek icin hemen Betzula’ya kat?l?n!
    707707+

  18. MathewDealf表示:

    Mostbet is a well-known platform providing a diverse selection of betting and casino games for users in Bangladesh Mostbet BD

  19. CurtisBam表示:

    mexican mail order pharmacies: Mexican Easy Pharm – purple pharmacy mexico price list

  20. Brandonnot表示:

    mexican mail order pharmacies: mexican mail order pharmacies – mexican drugstore online

  21. 10 Beautiful Graphics About Lawyer Asbestos asbestos lawsuit – pattern-wiki.win

  22. AmandaAscem表示:

    Discover the world of enjoyment with our pools!
    We offer a huge selection of pools, their installation and maintenance.
    More detailed information on the link купить песочный фильтр
    Create an oasis at home with high-quality solutions.
    Professional installation and guarantees for all work.

  23. CurtisBam表示:

    canadian pharmacy meds reviews: CanadianMdPharm – buy canadian drugs

  24. kawi777表示:

    What’s Going down i am new to this, I stumbled upon this I have
    discovered It positively useful and it has helped
    me out loads. I am hoping to give a contribution & aid
    other customers like its aided me. Good job.

發佈留言

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