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,365,461 Responses

  1. Dereketerm表示:

    can i purchase generic clomid pills: clomid – cost generic clomid for sale

  2. Nikefut表示:

    darknet seiten darknet seiten https://darknetmarketstore.com/ – blackweb official website

  3. BrandenSlomy表示:

    prednisone 50 mg for sale: generic Prednisone – prednisone 60 mg daily

  4. research ai表示:

    Fantastic beat ! I would like to apprentice while you amend your website, how can i subscribe for a blog site?
    The account aided me a appropriate deal. I have been a little bit
    familiar of this your broadcast offered shiny clear idea

    Stop by my web site: research ai

  5. StevenNub表示:

    can i order generic clomid without rx: buy clomid – where can i get cheap clomid pills

  6. Casino表示:

    Your way of explaining all in this post is actually pleasant, all be capable of easily understand it, Thanks a lot.

  7. StevenNub表示:

    dapoxetine price: cheap priligy – Priligy tablets

  8. Анна Черникова, индивидуальный психолог, предлагает онлайн-консультации для тех, кто хочет улучшить своё психологическое
    состояние и наладить отношения с окружающими.
    Она использует современные методы
    и техники, чтобы помочь своим клиентам справиться с такими проблемами как тревожные мысли и другими
    проблемами.
    Анна Черникова имеет высшее образование в области психологии и многолетний опыт работы с людьми разных возрастов и социальных групп.

  9. Blakesmema表示:

    кухни на заказ цены — Узнайте цены на изготовление кухонь на заказ с индивидуальным дизайном.

  10. So, you can search all latest promo codes directly here on proposed page,
    the https://johnvegascas.com,
    including latest No deposit casino bonus codes.

  11. BrandenSlomy表示:

    buy priligy: priligy maxpharm – dapoxetine online

  12. My spouse and I stumbled over here coming from a different web page and thought I may as well check things
    out. I like what I see so i am just following you. Look forward to exploring your web
    page repeatedly.

    My web page Deck Contractor Toronto

  13. 20 Reasons To Believe Private ADHD Diagnosis Will Never Be Forgotten private adhd diagnosis cost (http://www.deepzone.net)

  14. mau777表示:

    As the admin of this web site is working, no hesitation very
    shortly it will be renowned, due to its quality contents.

  15. baidat.com表示:

    Stop by my web-site; Daycares popular listings (baidat.com)

  16. Hi! I’ve been reading your web site for a while now and finally got the courage
    to go ahead and give you a shout out from Kingwood Tx!

    Just wanted to say keep up the excellent work!

  17. Hi, this weekend is good in favor of me, as this time i am reading this enormous educational post here
    at my residence.

  18. id=”firstHeading” class=”firstHeading mw-first-heading”>Search resᥙlts

    Heⅼp

    English

    Tools

    Tools
    moѵe to sidebar hide

    Actions

    Ԍeneral

    Also visit my blog … จัดดอกไม้แบบไทย

  19. If you desire to obtain a great deal from this piece
    of writing then you have to apply such methods to your won weblog.

    Here is my web page omegle alternatives

  20. BrandenSlomy表示:

    amoxicillin discount coupon: buy amoxil online – buy amoxicillin online cheap

  21. LamarFob表示:

    Medication reactions explained. Current medicine trends.
    buy proscar with no prescription
    Pill guide available. Get info now.

  22. چت ماه表示:

    When someone writes an paragraph he/she maintains the thought of a user in his/her mind
    that how a user can be aware of it. Therefore that’s why
    this piece of writing is great. Thanks!

  23. Sazrzsz表示:

    Легальная покупка диплома ПТУ с сокращенной программой обучения
    kherson.forum2x2.ru/login

  24. Medicines information leaflet. What side effects can this medication cause?
    where can i get cheap synthroid pills
    Actual news about drugs. Read here.

  25. Slot Mahjong表示:

    whoah this blog is magnificent i really like studying your
    articles. Keep up the good work! You realize, many people are hunting round for this info, you can help
    them greatly.

  26. BrandenSlomy表示:

    how to get cheap clomid pills: cheap clomid – how to buy generic clomid for sale

  27. 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. All the best

發佈留言

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