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,197,612 Responses

  1. phenq reviews表示:

    Very nice post. I just stumbled upon your blog and wanted to mention that I’ve really enjoyed surfing around your weblog posts.
    In any case I’ll be subscribing to your feed and I hope you write again very soon!

    Here is my web site :: phenq reviews

  2. Berniece表示:

    The 10 Most Scariest Things About Double Glazing Companies Near Me double glazing companies (Berniece)

  3. BomesJoype表示:

    Lorem Ipsum has been the industry’s standard dummy text https://hurtowniaamm.pl/ylflozx of type and scrambled it to make a type specimen book.

  4. I am sure this post has touched all the internet
    people, its really really good article on building up
    new blog.

    Also visit my homepage – billionaire brain wave reviews

  5. 3 Common Reasons Why Your Leather Couch With Chaise Isn’t Working
    (And How To Fix It) leather Sofa with chaise

  6. Medicine prescribing information. Drug Class.
    where to get cheap imodium for sale
    Some trends of medication. Read here.

  7. What NOT To Do When It Comes To The Double Glazing Showrooms Near Me Industry Upvc double glazed windows

  8. What’s The Job Market For Double Glazing Repairs Near Me Professionals Like?
    Double Glazing repairs near me

  9. Medication information leaflet. Long-Term Effects.
    can i order generic reglan for sale
    Actual about pills. Get now.

  10. The 9 Things Your Parents Teach You About Medical Malpractice Lawyer medical malpractice lawyer

  11. bonus code CSGOEmpire in Latvia

  12. Attorney表示:

    5 Killer Quora Answers On Medical Malpractice Attorneys Attorney

  13. Nowadays using instant messengers and social networks have become an integral part of our daily lives. But sometimes not dangerous to use Your real phone number to register in similar add-ons . Then virtual numbers can be a good solution

  14. SEO表示:

    Seo Software: Trying To Trap The Spiders. SEO

  15. Five Killer Quora Answers To Window Doctor Near Me window Doctor Near me

  16. 913875.xyz表示:

    A New Trend In Small Wood Burning Stoves 913875.xyz

  17. seo 마케팅表示:

    The A Person Must Know Concerning Seo seo 마케팅

  18. What’s The Job Market For Double Glazed Window Repairs Near Me Professionals?
    window Repairs Near me

  19. You’ll Be Unable To Guess Malpractice Lawyers’s Secrets malpractice Lawyers

  20. These are in fact enormous ideas in on the topic of blogging.

    You have touched some fastidious factors here. Any way keep up wrinting.

  21. Meds prescribing information. Brand names.
    where can i get generic clomid tablets
    All information about medicine. Read information now.

  22. AC repair表示:

    This article will help the internet people for creating new website or even a blog from start to end.

  23. Fantastic beat ! I would like to apprentice while
    you amend your website, how could i subscribe for a blog website?
    The account aided me a acceptable deal. I had been tiny bit acquainted of this your broadcast provided bright clear concept

  24. 20 Things You Must Know About Double Glazing Companies Near
    Me double Glazed door handle

  25. Dnrtgwt表示:

    Добрый день!
    Где приобрести диплом по необходимой специальности?
    Купить документ о получении высшего образования вы можете у нас в Москве. Мы предлагаем документы об окончании любых ВУЗов РФ. Вы сможете получить диплом по любой специальности, включая документы образца СССР. Гарантируем, что в случае проверки документов работодателем, каких-либо подозрений не появится.
    https://vadaszapro.eu/user/profile/1264230
    Хорошей учебы!

  26. You’ll Never Guess This Double Glazed Units Near Me’s
    Benefits double glazed Units near me (miamigaspe.ecrituresnumeriques.ca)

  27. You’ll Be Unable To Guess Double Glazed Units Near Me’s Tricks replacement double Glazed units near me

發佈留言

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