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,628,957 Responses

  1. Stephenpem表示:

    https://stromectol.fun/# buy stromectol uk

  2. JamesCof表示:

    lasix dosage: lasix medication – lasix furosemide 40 mg

  3. Looking For Inspiration? Try Looking Up GSA SEO VPS Gsa software seo

  4. Stephenpem表示:

    http://buyprednisone.store/# prednisone 1 mg for sale

  5. This is nicely expressed. .

  6. JamesCof表示:

    amoxicillin 500mg capsules price: generic amoxicillin – amoxicillin 500mg price canada

  7. JamesCof表示:

    amoxicillin 500 capsule: amoxicillin 500mg capsules price – where can i buy amoxicillin over the counter

  8. The 3 Most Significant Disasters In Double Glazing Window
    Replacement The Double Glazing Window Replacement’s 3
    Biggest Disasters In History Double Glazing Window Replacement

  9. DavidRak表示:

    furosemide 40mg Over The Counter Lasix lasix dosage

  10. sbobet表示:

    This is my first time visit at here and i am really pleassant to read all at one place.

  11. DavidRak表示:

    stromectol ireland stromectol pill for humans stromectol 3 mg price

  12. Vito表示:

    A motivating discussion іs defіnitely worth cⲟmment.
    I do beⅼieve that you ought to publish mߋre on tһis subject, іt
    mɑy not be a taboo matter but generally folks don’t discuss such subjects.
    To thе next! Kіnd reɡards!!

    My blog post; lotto bet; Vito,

  13. JamesCof表示:

    where can i get amoxicillin: amoxicillin 500 mg cost – amoxicillin canada price

  14. I’m extremely impressed with your writing skills as well as with the layout on yourblog. Is this a paid theme or did you customize it yourself?Either way keep up the nice quality writing, it’srare to see a great blog like this one nowadays.

  15. Stephenpem表示:

    https://buyprednisone.store/# where can i buy prednisone without a prescription

  16. Actually no matter if someone doesn’t be aware of afterward
    its up to other people that they will help, so here it occurs.

  17. Charlesdix表示:

    http://amoxil.cheap/# cost of amoxicillin 875 mg

  18. vk_com表示:

    Купить кондиционер в Рязани по лучшим ценам. Сплит-системы с гарантией до 5 лет от компании https://vk.com/kupit_kondicioner_ryazan

  19. LeonardFaulk表示:

    furosemide 40mg: lasix 100 mg tablet – buy lasix online

  20. Charlesmus表示:

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

  21. Link exchange is nothing else but it is only placing the other person’s web site link on your page
    at proper place and other person will also do same in support of
    you.

  22. Charlesdix表示:

    https://lisinopril.top/# lisinopril 40 coupon

  23. 188bet表示:

    My developer 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 WordPress on a number of websites for about a year and am worried about switching to another platform.
    I have heard fantastic things about blogengine.net.

    Is there a way I can transfer all my wordpress content into it?

    Any help would be greatly appreciated!

  24. Take A Look At One Of The Repair Double Glazed Windows Industry’s Steve Jobs Of The Repair Double Glazed Windows Industry repairs to
    upvc windows – https://vuf.minagricultura.gov.co/lists/informacin%20servicios%20web/dispform.aspx?id=7662164

  25. JamesCof表示:

    zestril cost price: medication lisinopril 20 mg – zestoretic 5 mg

  26. Greetings from Carolina! I’m bored to death at work so I decided to check out
    your blog on my iphone during lunch break. I love the knowledge you provide here and can’t wait
    to take a look when I get home. I’m amazed at how fast your blog loaded on my phone ..
    I’m not even using WIFI, just 3G .. Anyhow, wonderful
    blog!

  27. DavidRak表示:

    prednisone 5mg over the counter prednisone 20 tablet prednisone 50 mg buy

  28. JamesCof表示:

    prednisone over the counter cost: prednisone 20 mg pill – prednisone for sale

發佈回覆給「Vito」的留言 取消回覆

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