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,228,430 Responses

  1. Parking outside of the airport is, simply put, private parking at bwi.
    this will allow for you to receive a plan “B” and not will to force consumer at the last minute to look position in the parking lot.

  2. Best Tips For A Sensuous Nude Full Massage 제주밤문화

  3. surveypoint表示:

    continuously i used to read smaller articles or reviews that as well clear their motive,
    and that is also happening with this post which I am reading here.

    Also visit my web-site: surveypoint

  4. Darrelherse表示:

    en cok kazandiran slot siteleri: guvenilir slot siteleri 2024 – deneme bonusu veren slot siteleri

  5. 서면오피表示:

    Top 3 Health Benefits Of Massage 서면오피

  6. Wow, amazing blog layout! How long have you been blogging for?
    you make blogging look easy. The overall look of your web
    site is fantastic, as well as the content!

  7. KevinSounc表示:

    https://sweetbonanza.network/# sweet bonanza demo oyna

  8. ev taşıma表示:

    Evden Eve Nakliyat | Taşınma sürecinde doğru firma seçiminin ne kadar kritik olduğunu bu yazınızda çok güzel ifade etmişsiniz. Kozcuoğlu Evden Eve Nakliyat olarak, müşterilerimize en kaliteli hizmeti sunmak için buradayız.

  9. pronerve 6表示:

    It’s in fact very complex in this active life to listen news on TV,
    so I simply use the web for that reason, and take the hottest news.

    Feel free to surf to my web blog: pronerve 6

  10. RonaldDuS表示:

    פגישה. וכאן תזכה למגע חם שמסעיר את כל החושים, ומביא אותך לפורקן ושלווה. מאמר 4 נערות ליווי לעונג מקסימלי נערות ליווי, מחפש, הגעת אל המקום הנכון. כאשר אנחנו מדברים על נערות ליווי בתל אביב, אנחנו מדברים על עולם של עונג. יש כאן נערות מהארץ נערת ליווי בירושלים – פינוק כביר בעיר הבירה

  11. It’s in point of fact a nice and helpful piece of info.
    I’m glad that you shared this useful information with us.
    Please stay us up to date like this. Thank you for sharing.

    Also visit my blog post – genius wave review

  12. I am really impressed with your writing skills as
    well as with the layout on your weblog. Is this a paid theme or did you
    modify it yourself? Anyway keep up the excellent quality writing,
    it’s rare to see a great blog like this one these days.

  13. keys表示:

    See What Keys Programmed Tricks The Celebs Are Using keys

  14. Asking questions are in fact fastidious thing if you are not understanding
    something entirely, however this paragraph provides pleasant understanding yet.

  15. KevinSounc表示:

    https://slotsiteleri.bid/# slot siteleri

  16. gangbang indo表示:

    I’m really enjoying the theme/design of your weblog.
    Do you ever run into any browser compatibility problems?
    A number of my blog readers have complained about my blog
    not working correctly in Explorer but looks great in Safari.
    Do you have any ideas to help fix this issue?

  17. Here is my web-site; Daycares By Category (http://www.venuesathens.com)

  18. I simply could not depart your website before suggesting that I actually enjoyed the standard info an individual provide for your guests?
    Is going to be back regularly in order to inspect new posts

    Feel free to surf to my homepage; is herpesyl a cure

  19. Если вы искали где отремонтировать сломаную технику, обратите внимание – тех профи

  20. Darrelherse表示:

    bonus veren casino slot siteleri: oyun siteleri slot – guvenilir slot siteleri

  21. Excellent article. I’m going through many of these issues as well..

  22. KevinSounc表示:

    https://sweetbonanza.network/# sweet bonanza yorumlar

  23. Pills information sheet. Drug Class.
    synthroid tablet online
    Actual about pills. Read here.

  24. SCAM表示:

    My brother suggested I might like this blog. He was entirely right.
    This post truly made my day. You can not imagine just how
    much time I had spent for this information! Thanks!

發佈留言

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