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,523,449 Responses

  1. Trefihx表示:

    Приобретение школьного аттестата с официальным упрощенным обучением в Москве
    l90226mw.beget.tech/2024/10/14/kupit-diplom-bez-posescheniya-uchebnogo-zavedeniya.html

  2. What’s Everyone Talking About Pragmatic Slot Manipulation Right Now 프라그마틱 이미지

  3. Williamagric表示:

    cheap erectile dysfunction pill http://indianpharm24.pro/# top 10 pharmacies in india

  4. Treffgi表示:

    Приобретение школьного аттестата с официальным упрощенным обучением в Москве
    kinderby.mybb.ru/viewtopic.php?id=5144#p120780

  5. LeroyBak表示:

    reputable indian pharmacies indian pharmacy purchase online reputable indian online pharmacy

  6. LeroyBak表示:

    buy medicines online in india India pharmacy delivery pharmacy website india

  7. The One Togel Resmi Indonesia Mistake That
    Every Newbie Makes Situs toto Togel

  8. Williamagric表示:

    ed meds online canada http://indianpharm24.pro/# buy medicines online in india

  9. Thanks for another informative web site. Where else could
    I am getting that kind of information written in such a perfect way?
    I’ve a challenge that I am just now operating on, and I’ve been on the look out for such information.

  10. slot gacor表示:

    I visited various web pages however the audio feature for audio songs current
    at this web page is genuinely wonderful.

  11. Heya i’m for the first time here. I found this board and I find It really useful & it
    helped me out a lot. I hope to give something back and
    help others like you helped me.

  12. Treftsf表示:

    Процесс получения диплома стоматолога: реально ли это сделать быстро?

    fauna.0pk.me/viewtopic.php?id=1624#p6628

  13. Treftqk表示:

    Как приобрести диплом о среднем образовании в Москве и других городах
    alternativaprofi.com/forum/viewthread.php?thread_id=34746

  14. LeroyBak表示:

    buy canadian drugs low cost pharmacy generic ed drugs

  15. Deloras表示:

    7 Little Changes That’ll Make The Difference With Your Accident
    Attorney accident lawyers (Deloras)

  16. LeroyBak表示:

    mexican mail order pharmacies mexico pharmacy mexican pharmaceuticals online

  17. Diplomi_wyOl表示:

    купить дипломы в ставрополе недорого diplomdarom.ru .

  18. Why We Do We Love Compact Single Stroller (And You Should Also!) single Fold pushchair (http://goodjobdongguan.com/)

  19. borschevik.Ru表示:

    5 Tools That Everyone Working Involved In Audi A4 Key Replacement Industry Should Be
    Using audi keyless go; borschevik.Ru,

  20. Diplomi_zmOl表示:

    купить диплом в тобольске diplomdarom.ru .

  21. BrandonSaisy表示:

    medication from mexico pharmacy: mexico pharmacy – mexico drug stores pharmacies

  22. Williamagric表示:

    pumps for ed https://indianpharm24.pro/# reputable indian pharmacies

  23. Trefkny表示:

    Быстрое обучение и получение диплома магистра – возможно ли это?
    domainrama.com/read-blog/4709

  24. 30 Inspirational Quotes On What Causes Mesothelioma Other
    Than Asbestos Mesothelioma Attorney

  25. n666表示:

    Hey! I understand this is kind of off-topic but I needed
    to ask. Does building a well-established website such as yours take
    a massive amount work? I’m brand new to running a blog however I do write in my diary every day.
    I’d like to start a blog so I can share my own experience
    and views online. Please let me know if you have any
    kind of ideas or tips for brand new aspiring blog owners.
    Thankyou!

發佈留言

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