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,451,400 Responses

  1. athletic tape表示:

    Newly dripped pictures of the Google Pixel 9a provide us an idea of what
    Google’s mid-range Pixel tool will certainly resemble.

  2. kypit 1s_nzEn表示:

    настроить 1с бухгалтерия цена https://svarog.forum24.ru/?1-0-0-00000330-000-0-0/ .

  3. Jemmawara表示:

    Используйте официальную версию мостбет для ставок на спорт и получите доступ к самым актуальным коэффициентам и лучшим условиям для игроков.

  4. Brandonnot表示:

    Indian Cert Pharm: mail order pharmacy india – Indian pharmacy that ships to usa

  5. Brandonnot表示:

    prescription drugs canada buy online: CanadianMdPharm – legitimate canadian mail order pharmacy

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

  7. JacobLoody表示:

    http://nedra2021.ru — создаём стильные и функциональные кухни.

  8. Mat6tube表示:

    Mat6tube I like the beneficial details you offer in your content

  9. Hi it’s me, I am also visiting this web page daily, this web page
    is in fact good and the people are actually sharing nice thoughts.

  10. Brandonnot表示:

    Online pharmacy: indian pharmacy online – Indian pharmacy that ships to usa

  11. Michaelallek表示:

    Виртуальные номера становятся все более популярными как среди частных пользователей, так и в бизнес-среде. Эти номера позволяют принимать звонки и SMS, а также использовать их для регистрации в различных сервисах без необходимости привязываться к физическому номеру телефона. Технология основывается на использовании IP-телефонии, что дает пользователю массу преимуществ по сравнению с традиционными номерами купить номер для ватсап

  12. Lizzie Cross表示:

    Excited learning potential benefits derived from combining multiple modalities together during visits made towards reputable medi-spa establishments offering diverse range options available nowadays… let us know which ones work best according individual custom facials vs standard facials

  13. Best Fridges表示:

    10 No-Fuss Strategies To Figuring Out Your Fridges & Freezers Best Fridges

  14. CurtisBam表示:

    Indian pharmacy that ships to usa: Best Indian pharmacy – Best Indian pharmacy

  15. betflix22表示:

    Hello everybody, here every one is sharing these experience,
    therefore it’s nice to read this blog, and I used to go to see this weblog daily.
    betflix22

  16. denticore表示:

    Do you mind if I quote a couple of your articles as
    long as I provide credit and sources back to your site? My blog
    is in the exact same niche as yours and my visitors would truly benefit from a lot of the information you present here.

    Please let me know if this ok with you. Thanks a lot!

  17. Brandonnot表示:

    Mexican Easy Pharm: Mexican Easy Pharm – medicine in mexico pharmacies

  18. OP表示:

    Body Massage OP

  19. 8 Tips To Increase Your 3 Wheeled Pushchair Game 3 wheel Pushchair

  20. The importance of proper drainage in commercial roofing cannot be overlooked! More info available at vinyl siding options

  21. CurtisBam表示:

    canada drugs reviews: canadian pharmacy phone number – canadian neighbor pharmacy

  22. Mitzi表示:

    10 Facts About Evolution Slot That Can Instantly
    Put You In An Optimistic Mood 에볼루션 카지노 (Mitzi)

  23. Brandonnot表示:

    Best online Indian pharmacy: Indian Cert Pharm – Indian pharmacy that ships to usa

發佈留言

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