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,516 Responses

  1. Moises表示:

    Body Massage 오피 (Moises)

  2. CurtisBam表示:

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

  3. Brandonnot表示:

    canadian pharmacy world: CanadianMdPharm – online canadian drugstore

  4. Brandonnot表示:

    canadian pharmacy near me: CanadianMdPharm – canadian drug pharmacy

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

  6. Michaelgence表示:

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

  7. CurtisBam表示:

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

  8. 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

  9. 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.

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

  11. Carrolleruck表示:

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

  12. Brandonnot表示:

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

  13. 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+

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

    https://www.extra-plonsk.pl

  15. 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!

  16. 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!!

  17. CurtisBam表示:

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

  18. 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!

  19. Derrick Myers表示:

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

發佈留言

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