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

  1. Wallacefex表示:

    en kazancl? slot oyunlar?: guvenilir slot siteleri – slot oyunlar? puf noktalar?

  2. Rafaela表示:

    Good post. I learn something new and challenging on websites I stumbleupon everyday.
    It’s always exciting to read articles from other writers and practice a little
    something from their sites.

  3. PARABU 99表示:

    Hurrah! In the end I got a web site from where I be capable of in fact
    obtain useful information concerning my study and knowledge.

  4. 용인호빠表示:

    존버가 답이다!! 용인에 유일하게 생존하고 있는 용인호빠의 생존력을 한번 느껴 보실래요?

  5. Porn Sex表示:

    Hmm it seems like your site ate my first comment (it was extremely long) so I guess I’ll just sum it up what I wrote and say, I’m thoroughly enjoying your blog.
    I as well am an aspiring blog writer but I’m still new to everything.
    Do you have any points for rookie blog writers?

    I’d genuinely appreciate it.

  6. Wallacefex表示:

    sweet bonanza kazanma saatleri: sweet bonanza yorumlar – sweet bonanza yorumlar

  7. Trade Max Air表示:

    I think this is among the most significant information for me.
    And i am glad reading your article. But want to remark on some general things, The web site style
    is ideal, the articles is really nice : D. Good job, cheers

  8. Your Family Will Thank You For Having This Bmw Key Fob Replacement
    Cost Replacement Bmw Key Fob

  9. Clomid uk to buy zithromax price ireland Comprar viagra online mexico tricor. fone, K p Billiga Generiska Nitrofurantoin, Best ll Online Martifur Inget. Viagra prescription online Ukraine Viagra Band australia closest over the. Kцp Medicinering Hur Mycket Kostar Generisk Ciprofloxacin 750mg. Hvor Bestiller Billig Tadalafil Ingen Receptplig, First Ladies London. Bestil Pе Nettet Keflex Uden Recept, Bestil Generisk Keflex 500mg Uden. Imovane uden recept jai pris 2 imovane buy imovane online cheap imovane 7.5. Online Pills Store. https://lavprismedicin.space/colrefuz/ Kobe Colrefuz Recept

  10. BradleyEdino表示:

    slot oyunlar? slot oyunlar? puf noktalar? slot oyunlar?

  11. Orval表示:

    Unquestionably consider that which you stated.
    Your favourite justification seemed to be on the internet the simplest thing
    to have in mind of. I say to you, I certainly get annoyed at the same time
    as other people think about concerns that they just do not understand about.
    You managed to hit the nail upon the highest and defined out the whole thing without having side effect , people can take a signal.
    Will likely be back to get more. Thank you

  12. Cyrus表示:

    VIP Experience 유흥사이트, Cyrus,

  13. Scottmeali表示:

    Виртуальный номер телефона даёт возможность подключать любое количество номеров и разговаривать с любого устройства, принимать звонки в офисе или дома купить номер для Авито

  14. Like Aqualyx, medical professionals infuse Kybella to treat a dual chin.

  15. Orlando表示:

    Hi! Do you know if they make any plugins to
    protect against hackers? I’m kinda paranoid
    about losing everything I’ve worked hard on. Any tips?

  16. Dannyfut表示:

    dark web markets deep web markets tor markets

  17. вывод. из. запоя. на. дому. ростов. https://vyvod-iz-zapoya-rostov27.ru .

  18. I lately went to a Brazilian steakhouse, and the flavors were out of this world! The selection of meats went over brazilian steakhouse tempe

  19. 24 Hours To Improving Best Car Accident Lawyer Near Me car Wreck attorney

  20. Wallacefex表示:

    en guvenilir casino siteleri: deneme bonusu veren casino siteleri – superbetin giriЕџ

  21. Wallacefex表示:

    en cok kazand?ran slot oyunlar?: slot siteleri – slot siteleri

  22. I’ve been surfing on-line more than 3 hours today, but I
    never found any interesting article like yours.
    It’s lovely price enough for me. In my view,
    if all webmasters and bloggers made good content
    as you did, the web will probably be much more helpful than ever before.

  23. splashpools表示:

    Nice blog here! Also your site loads up very fast!
    What web host are you using? Can I get your affiliate link to your host?

    I wish my site loaded up as fast as yours lol

  24. Franklin Cobb表示:

    Great process explaining the role of tow vehicles in accident recuperation! I stumbled on a funky hyperlink that qualities truly-existence memories from towing authorities affordable tow truck service

  25. Dannyfut表示:

    black internet the dark internet dark web links

發佈留言

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