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,666,953 Responses

  1. https://filedn.eu/lXvDNJGJo3S0aUrNKUTnNkb/bogin9/research/bogin9-(108).html
    Trust us, with a enjoyable handkerchief hem and fairly flutter sleeves, you may be getting compliments all night.

  2. With thanks! I value it!

  3. Thanks for sharing such a pleasant opinion, post is pleasant,
    thats why i have read it entirely

  4. Teodoro Adler表示:

    https://bogin5.z7.web.core.windows.net/research/bogin5-(38).html
    Searching for off-the-shoulder necklines or long sleeves?

  5. Ӏ wаnted to thɑnk yoᥙ for this wonderful read!! I certaiinly enjoyed every little bit of it.
    Ι have уou bookmarked to look at neѡ tһings you post…

    My web blog: jasa followers pinterest

  6. Vicky Hawes表示:

    https://chinavisa31.z31.web.core.windows.net/research/chinavisa31-(55).html
    Many women are concerned about exposing their higher arms.

  7. Rocky Morton表示:

    Wonderful post! We will be linking to this great post on our website. Keep up the good writing.

    Feel free to surf to my web site – billiards apparel [https://social.msdn.microsoft.com/Profile/bidathinhkent]

  8. Anda bisa menyimpan video dari instagram dengan mudah dan cepat baik tanpa maupun dengan bantuan aplikasi.

  9. Hi I am so glad I found your blog, I really found you by error, while I was researching
    on Google for something else, Anyways I am
    here now and would just like to say thank you for a tremendous post and a all
    round entertaining blog (I also love the theme/design), I don’t have time to
    read it all at the moment but I have bookmarked it and also added your RSS feeds, so when I have
    time I will be back to read much more, Please do keep up the great work.

  10. I’m not sure why but this web site is loading extremely slow for
    me. Is anyone else having this issue or is it a issue
    on my end? I’ll check back later on and see if the problem still exists.

  11. I used to be suggested this blog by way of my cousin. I
    am no longer positive whether this post is written via him as nobody else understand such
    certain about my trouble. You’re incredible! Thank you!

  12. psyxyou表示:

    Benevolentiae captande causa — Для снискания благоволения.
    https://batmanapollo.ru

  13. Zhurmency表示:

    “”Сказочное существо” — это фантастическое существо, талантливо вылепленное в мире фантазии. Его особенный внешность объединяет особенности разнообразных тварей и элементы естества, наделяя ему загадочный и волшебный внешний вид. Тело https://t.me/zhurnalus облачено мягкой, переливающейся покровом, что меняет цвет в согласно от своего настроения и внешней среды обитания. Его огромные, глубокие глаза сияют яркими цветами, показывая свое любопытство и ум. Такое создание обладает невероятной способностью воспринимать и взаимодействовать с разными разновидностями существования, преобразуя его действительно неповторимым жителем его собственного волшебного мира.

  14. I really like your blog.. very nice colors & theme. Did you create
    this website yourself or did you hire someone to do it for you?
    Plz answer back as I’m looking to create my own blog and would like to know where u got this from.
    appreciate it

  15. you are actually a good webmaster. The web site loading speed
    is amazing. It kind of feels that you are
    doing any distinctive trick. Also, The contents are masterpiece.

    you have performed a great job on this matter!

  16. 789win表示:

    Có 789win có thể sử dụng tiền thưởng từ mới đến cũ đều có tại nhà
    cái. Khuyến mãi đặc biệt hoặc thực hiện lần nạp tiền vào 789win chọn hàng thanh toán. Hỗ trợ giải đấu mà bạn chọn tùy chọn nạp tiền để bắt đầu cuộc hành trình.
    Bước 7 quay lại trang tải app 789win hỗ trợ từ nhà cung cấp.
    Về mặt sự phục vụ hỗ trợ tốt nhất như giao
    dịch quy định. Với phòng game nổ hũ đều mang
    đến những sự kiện này người chơi.
    Kèo cược hấp dẫn người tham gia cũng đang ngày càng tăng cao.

    Đăng ký ở nước Ngoài cũng công bố từng kèo cược được rồi.
    Ngoài phiên bản bắn cá mà tại 789win còn được tổ chức thường xuyên nhằm mục.
    Ngoài thế mạnh là cá độ 789 WIN một số tổ chức khác.

    Nhìn chung nhà cái WIN 789 WIN mang đến một trải nghiệm người dùng.
    Hoạt động với hình thức giới hạn cho phép của người chơi truy cập.
    Luôn nhận định của mình qua việc giành được giấy phép lái xe hoặc chứng minh.
    Bạn đang có kết nối tại bảng ODDS 789win cho phép người chơi.

  17. Rug Cleaning表示:

    Hi there Dear, are you truly visiting this site on a regular basis, if so then you will
    definitely take good experience.

  18. free dating表示:

    This site definitely has all the information I wanted concerning
    this subject and didn’t know who to ask.

  19. WOW just what I was searching for. Came here by searching for trash chute
    door latches

  20. porn pics表示:

    Touche. Great arguments. Keep up the great work.

  21. MichaelOwend表示:

    Paxlovid buy online: buy paxlovid – buy paxlovid online

  22. Nilda表示:

    throat cancer caused by railroad how to get a settlement
    (Nilda)

  23. Chef Thierry表示:

    Your way of telling everything in this article is in fact good, all be
    capable of easily understand it, Thanks a lot https://chefthierry.ca/plats-cuisines-congeles/

  24. %%

    Feel free to visit my blog post Greenpower Zt500 (http://Www.C1Aid4A5E.рф)

  25. Hello there! This blog post could not be written much better!
    Looking at this article reminds me of my previous roommate!
    He always kept talking about this. I am going to forward this information to him.
    Fairly certain he will have a very good read. Many thanks
    for sharing!

  26. Hiram表示:

    asbestos cancer lawsuit lawyer mesothelioma settlement (Hiram)

  27. https://bogin58.z13.web.core.windows.net/research/bogin58-(31).html
    The site’s subtle robes make for glorious evening put on that’ll serve you lengthy after the marriage day.

發佈回覆給「cost of Adhd assessment」的留言 取消回覆

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