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,364,531 Responses

  1. How To Make An Amazing Instagram Video About Coffee Machine Best what coffee machine is The best

  2. Rosa Gregory表示:

    I found this very interesting. For more, visit pressure washing company

  3. Предлагаем услуги профессиональных инженеров офицальной мастерской.
    Еслли вы искали ремонт телефонов infinix рядом, можете посмотреть на сайте: ремонт телефонов infinix
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  4. DanielAbice表示:

    http://amoxstar.com/# amoxicillin 500

  5. Thanks for your marvelous posting! I really enjoyed reading it, you will be a great author.
    I will make sure to bookmark your blog and definitely will come back from now on. I want to encourage that you continue
    your great job, have a nice morning!

  6. SamuelBix表示:

    prednisone medication: PredniBest – 10 mg prednisone

  7. Предлагаем услуги профессиональных инженеров офицальной мастерской.
    Еслли вы искали ремонт телефонов infinix, можете посмотреть на сайте: ремонт телефонов infinix
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  8. RobertJar表示:

    prednisone buy without prescription: canada buy prednisone online – prednisone tablet 100 mg

  9. Sally Fields表示:

    It’s amazing how home care can provide peace of mind for families in Mesa home care assistance bellevue

  10. Vera Hayes表示:

    Has anyone else used raid data recovery for data recovery in Orange County? I had a great experience with

  11. Very soon this web page will be famous amid all blog visitors, due to it’s fastidious posts

  12. SamuelBix表示:

    amoxicillin 875 125 mg tab: AmoxStar – amoxicillin 500mg pill

  13. This article has motivated me to take action on my dream deck project—I can’t wait to get started with your tips from here: Custom Deck Builders

  14. Cameron Wise表示:

    Cleaned out my attic with the help of junk removal

  15. Sellvia表示:

    Tremendous issues here. I am very happy to peer your post.
    Thanks a lot and I am looking forward to touch you. Will
    you kindly drop me a mail?

  16. Предлагаем услуги профессиональных инженеров офицальной мастерской.
    Еслли вы искали ремонт телефонов infinix в москве, можете посмотреть на сайте: ремонт телефонов infinix цены
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  17. After I initially left a comment I seem to have clicked the
    -Notify me when new comments are added- checkbox and now each
    time a comment is added I receive 4 emails with the exact same comment.
    Is there a way you can remove me from that service?

    Thank you!

  18. Merci encore ! Vos conseils concernant la sécurité domestique sont très appréciés ici ! serrurier bordeaux centre

  19. Hattie Nunez表示:

    I appreciate that furniture removal gives back by donating usable items they collect

  20. I wanted to thank you for this great read!! I certainly loved every
    little bit of it. I have you saved as a favorite to
    check out new stuff you post…

  21. I love your blog.. very nice colors & theme. Did you design this website yourself or did you
    hire someone to do it for you? Plz reply as I’m looking
    to construct my own blog and would like to find out where u got this from.
    kudos https://Rollaas.id/2024/12/12/une-galerie-didees-inspirantes-pour-la-gourmandises/

  22. Ӏ delkight in, leawd tⲟo I found exaсtly whzt I ussed tto bbe taking a lopok for.

    Yօu’ve endded myy fohr dday lpng hunt! Godd Bleess yⲟuu man. Havve a
    nce day. Bye

    Feelⅼ ffree tto isit myy ᴡweb site … خرید آنلاین با تخفیف

  23. Nikefut表示:

    darknet market lists darknet market lists dark market url

  24. akartoto表示:

    Excellent web site. A lot of helpful info here. I am sending it to several pals ans additionally sharing in delicious.
    And certainly, thanks to your effort!

  25. Jason Pittman表示:

    Just got my inspection results back from Island Home Inspections Termite control Puerto Rico inspections

  26. SamuelBix表示:

    cheap clomid: clomid on pharm – can i order generic clomid without insurance

  27. SamuelBix表示:

    prednisone no rx: buy prednisone no prescription – 10 mg prednisone tablets

  28. Wow that was unusual. I just wrote an extremely long comment but after I clicked submit my comment didn’t appear.
    Grrrr… well I’m not writing all that over again. Anyways, just wanted to say superb blog!

發佈留言

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