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,245,260 Responses

  1. Drug information. Short-Term Effects.
    can i purchase azathioprine price
    All information about drug. Read information now.

  2. Bradleygoath表示:

    buy prednisone without prescription paypal generic Prednisone prednisone 20 mg tablets

  3. Laskar303表示:

    This is a topic that’s neаr tⲟ mmy heart…

    Takе care! Wһere aгe үoᥙr contact details though?

    Мy web blog Laskar303

  4. Guide To Treadmill Fold Up: The Intermediate
    Guide For Treadmill Fold Up Treadmill Fold Up

  5. Bradleygoath表示:

    cheap priligy max pharm priligy max pharm

  6. 25 Amazing Facts About Free Pragmatic 프라그마틱 순위

  7. врач нарколог на дом платный https://motik13.0pk.me/viewtopic.php?id=1995 .

  8. Wymagania Prawne Na Posiadanie Licencji Jazdy Na Traktor Z Przyczepą
    Prawo Jazdy Na Traktor Z Przyczepą: Wszystko, Co Musisz Wiedzieć Prawo Jazdy na traktor

  9. Hey There. I found your blog using msn. This is an extremely well written article.
    I will make sure to bookmark it and come back to read more of your useful info.
    Thanks for the post. I’ll certainly comeback.

  10. Узнай все о лапароскопия варикоцеле признаки варикоцеле

  11. Nikefut表示:

    tor markets links tor market darkmarkets

  12. Uazrstg表示:

    Диплом техникума купить официально с упрощенным обучением в Москве

    betterbodies2.store/kupit-attestat-starogo-obraztsa-v-orenburge.html

  13. DavidShoks表示:

    GasDank is your go-to for ordering weed online in Canada. We are a safe and discreet marijuana mail order service based in Toronto, Ontario, also offering same-day delivery throughout the GTA https://a2s.in/redirect-to/?redirect=https://gasdank.com/store-locator/

  14. Dereketerm表示:

    cost of amoxicillin 875 mg: amoxil com pharm – amoxicillin from canada

  15. Markdob表示:

    Всем привет! Может кто знает, где почитатьразные статьи о недвижимости? Сейчас читаю – https://avgust-shop.ru

  16. This is a topic that is near to my heart… Best wishes!
    Exactly where are your contact details though?

  17. super177表示:

    Kudos, Helpful information.

  18. Markdob表示:

    Всем привет! Может кто знает, где почитатьразные блоги о недвижимости? Пока нашел – https://avgust-shop.ru

  19. Opalnirvana表示:

    I’m not that much of a online reader to be honest but your sites really nice, keep it up!
    I’ll go ahead and bookmark your site to come back later. Many thanks

  20. BrandenSlomy表示:

    prednisone 20mg for sale: cheap prednisone – prednisone 10

  21. Bridgett表示:

    The Top Reasons Why People Succeed In The Car Accident Case Industry
    attorney car accident near me [Bridgett]

  22. go to my blog表示:

    It is not my first time to pay a quick visit this
    web page, i am browsing this site dailly and get good data
    from here all the time.

  23. Markdob表示:

    Приветствую. Может кто знает, где найтиполезные блоги о недвижимости? Сейчас читаю – https://avgust-shop.ru

  24. BrandenSlomy表示:

    buy cheap amoxicillin online: Com Pharm – can you buy amoxicillin over the counter in canada

  25. Iyannaobesk表示:

    fortune mouse gratis
    fortune mouse gratis слот

  26. StevenNub表示:

    amoxicillin 500 mg tablets: Amoxicillin buy online – medicine amoxicillin 500

  27. 15 Amazing Facts About Mesothelioma Asbestos Lung Cancer Mesothelioma lawyer

發佈留言

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