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,447,919 Responses

  1. Quantum Trust表示:

    Write more, thats all I have to say. Literally, it seems as though you relied
    on the video to make your point. You obviously know what
    youre talking about, why throw away your intelligence on just posting
    videos to your site when you could be giving us something enlightening to read?

  2. Antoniofep表示:

    Betzula, canl? bahis konusunda benzersiz secenekler sunar. en heyecanl? maclar icin guvenli bir sekilde yuksek oranlar? kesfedebilirsiniz.

    Betzula’n?n yuksek guvenlik onlemleri, sorunsuz bir deneyim sunar. Bet Zula sosyal medya hesaplar?yla bonus f?rsatlar?ndan haberdar olabilirsiniz.

    favori futbol kuluplerinizin bahislerinizi an?nda yapabilirsiniz.

    Ayr?ca, Betzula guncel giris adresi, mobil cihazlar uzerinden kolay erisim sunar. Ozel olarak, betzula twitter, profesyonel bir deneyim saglar.

    Betzula, en genis bahis seceneklerinden ozel turnuvalara kadar profesyonel bir hizmet sunar. favori tak?m?n?z?n galibiyetini kutlamak icin simdi giris yap?n!
    707707+

  3. Brandonnot表示:

    mexican online pharmacies prescription drugs: mexico drug stores pharmacies – п»їbest mexican online pharmacies

  4. CurtisBam表示:

    canadian pharmacy uk delivery: CanadianMdPharm – buy canadian drugs

  5. Rollaas.id表示:

    You need to be a part of a contest for one of the finest blogs on the
    net. I will recommend this web site! https://Rollaas.id/2024/12/20/the-ultimate-guide-to-applying-for-student-loans-in-bc/

  6. Antoniofep表示:

    Betzula guncel giris, en populer bahis platformu konusunda ustun f?rsatlar sunar. en heyecanl? maclar icin Betzula giris yaparak canl? bahis oynamaya baslayabilirsiniz.

    Betzula’n?n guvenilir altyap?s?, her cihazdan erisim imkan? tan?r. guncel duyurular? kac?rmadan en son haberlerden haberdar olabilirsiniz.

    favori futbol kuluplerinizin bahislerinizi an?nda yapabilirsiniz.

    Ayr?ca, platformun en yeni versiyonu, mobil cihazlar uzerinden kolay erisim sunar. Ozel olarak, fenerbahce galatasaray betzula, kolay ve h?zl? giris imkan?.

    Betzula, en genis bahis seceneklerinden ozel turnuvalara kadar tum kullan?c?lar?n ihtiyaclar?n? kars?lar. en guncel oranlar? gormek icin Betzula ile kazanmaya baslay?n!
    707707+

  7. вывод из запоя в стационаре [url=http://vyvod-iz-zapoya-v-stacionare21.ru]вывод из запоя в стационаре[/url] .

  8. Moises表示:

    Body Massage 오피 (Moises)

  9. CurtisBam表示:

    mexico drug stores pharmacies: mexican rx online – п»їbest mexican online pharmacies

  10. Brandonnot表示:

    canadian pharmacy world: CanadianMdPharm – online canadian drugstore

  11. Brandonnot表示:

    canadian pharmacy near me: CanadianMdPharm – canadian drug pharmacy

  12. выведение из запоя воронеж стационар [url=http://www.vyvod-iz-zapoya-v-stacionare-voronezh24.ru]выведение из запоя воронеж стационар[/url] .

  13. Michaelgence表示:

    Имплантация — популярная процедура замещения зубов искусственными аналогами. Стоматологическая имплантология является одним из важнейших разделов современной стоматологии, предусматривающий восстановление нарушений целостности зубочелюстной системы благодаря качественным аллопластическим материалам и достижениям в области современной стоматологии имплантация зубов импланты

  14. CurtisBam表示:

    Indian pharmacy international shipping: Indian Cert Pharm – Best online Indian pharmacy

  15. Hello there! This is kind of off topic but I need some guidance from
    an established blog. Is it very difficult to set up your own blog?
    I’m not very techincal but I can figure things out pretty fast.
    I’m thinking about making my own but I’m not
    sure where to begin. Do you have any ideas or suggestions?
    Cheers https://calm-Shadow-f1b9.626266613.Workers.dev/cfdownload/http://cgi3.bekkoame.ne.jp/cgi-bin/user/b112154/cream/yybbs.cgi?list=thread

  16. Thanks for some other magnificent article.
    The place else may just anyone get that type of information in such a perfect manner
    of writing? I’ve a presentation subsequent week,
    and I’m at the look for such info.

  17. вывод из запоя в стационаре нижний новгород вывод из запоя в стационаре нижний новгород .

  18. Carrolleruck表示:

    https://mexicaneasypharm.com/# medicine in mexico pharmacies
    canadian pharmacy phone number

  19. Brandonnot表示:

    pet meds without vet prescription canada: Canadian Md Pharm – vipps canadian pharmacy

  20. Antoniofep表示:

    Betzula giris, en populer bahis platformu konusunda yenilikci cozumler sunar. Fenerbahce Galatasaray derbisi icin guvenli bir sekilde kazanma sans?n?z? art?rabilirsiniz.

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

    en onemli spor etkinliklerinin bahislerinizi an?nda yapabilirsiniz.

    Ayr?ca, platformun en yeni versiyonu, mobil cihazlar uzerinden kolay erisim sunar. Ozel olarak, https://apsistek.com/mobil/ – betzula twitter, tum bahis severler icin en iyi cozum.

    Betzula, spor bahislerinden canl? casino oyunlar?na kadar en iyi deneyimi yasatmay? amaclar. en guncel oranlar? gormek icin simdi giris yap?n!
    707707+

  21. Really helpful….looking forward to coming back.

    https://www.extra-plonsk.pl

  22. My coder is trying to persuade me to move to .net
    from PHP. I have always disliked the idea because of the expenses.

    But he’s tryiong none the less. I’ve been using Movable-type on a variety
    of websites for about a year and am concerned about switching to another platform.
    I have heard very good things about blogengine.net. Is there a way
    I can import all my wordpress content into it? Any help would be really appreciated!

  23. Hi, i think that i noticed you visited my website thus i came to
    return the choose?.I am attempting to to find things to
    enhance my web site!I guess its good enough to make use of a
    few of your concepts!!

  24. CurtisBam表示:

    best online pharmacies in mexico: Mexican Easy Pharm – Mexican Easy Pharm

  25. Fantastic blog! Do you have any tips and hints for aspiring writers?
    I’m hoping to start my own website soon but I’m a little lost on everything.
    Would you recommend starting with a free platform like WordPress or go for a paid option? There are so
    many options out there that I’m totally confused ..
    Any suggestions? Many thanks!

  26. Derrick Myers表示:

    Thanks for the valuable insights. More at متن روز پدر برای استوری

發佈留言

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