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,525,360 Responses

  1. Diplomi_riOl表示:

    купить диплом в пушкино diplomdarom.ru .

  2. Diplomi_rjel表示:

    купить диплом о высшем образовании в самаре [url=https://man-diploms.ru/]man-diploms.ru[/url] .

  3. LeroyBak表示:

    generic ed pills low cost prescription ed remedies

  4. Для тех, кто хочет грузоперевозки Новосибирск Томск, попутные маршруты обеспечат экономию.

  5. Jorgeagopy表示:

    buy prescription drugs from india: India pharmacy international – indian pharmacy online

  6. LeroyBak表示:

    ed pills that really work cheap pharmacy male erectile dysfunction

  7. Williamagric表示:

    erectial disfunction https://indianpharm24.pro/# reputable indian pharmacies

  8. Diplomi_eyOl表示:

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

  9. Hey! I realize this is kind of off-topic however I had to ask.
    Does running a well-established blog such as yours require a large amount of
    work? I am completely new to writing a blog but I do
    write in my journal everyday. I’d like to start a blog so I can easily share my own experience and views online.
    Please let me know if you have any suggestions or tips for brand
    new aspiring blog owners. Appreciate it!

  10. Diplomi_dnma表示:

    диплом специалиста купить диплом специалиста купить .

  11. Diplomi_qcma表示:

    можно ли поступить с купленным дипломом landik-diploms.ru .

  12. Gregory表示:

    The routes to trying to get a Canadian Gregory are
    distinct for important people that applying. You’ll need to from the
    form to see what merchandise is needed for you to fill the form.

    Feel free to surf to my page – immigation; Gregory,

  13. slot表示:

    Keep on working, great job!

  14. slot gacor表示:

    Hello my loved one! I want to say that this post is awesome, great written and include almost all vital infos.

    I’d like to look more posts like this .

  15. Treadmill Folding Incline Tips To Relax Your Everyday Lifethe Only Treadmill Folding Incline Trick That Everybody
    Should Know treadmill Folding incline

  16. Dixie表示:

    See What Contemporary Pellet Stove Tricks The Celebs Are Utilizing contemporary pellet stove (Dixie)

  17. Meds information for patients. Drug Class.
    order generic bactrim prices
    Some about pills. Read now.

  18. Diplomi_ieOl表示:

    купить аттестаты за 11 класс недорого купить аттестаты за 11 класс недорого .

  19. Google.Fm表示:

    Sports Toto Korea Tips From The Best In The Business 토지노 사이트, Google.Fm,

  20. Fantastic items from you, man. I’ve consider your stuff
    prior to and you are just too magnificent. I actually like what
    you have got right here, certainly like what you’re saying and the best way by which you are saying it.
    You’re making it enjoyable and you still take care of
    to stay it wise. I can not wait to read much more from you.
    This is actually a tremendous site.

  21. voiceof.com表示:

    15 Of The Top Sofas Sectionals Bloggers You Must
    Follow apartment Size sectional sofa (voiceof.com)

  22. Medicine information. Cautions.
    where buy cheap risperdal pills
    Everything information about medicines. Read now.

  23. Diplomi_shOl表示:

    дипломная работа купить diplomdarom.ru .

  24. 10 L Shaped Chesterfield Sofa-Friendly Habits
    To Be Healthy antique Chesterfield sofa

  25. slot表示:

    Hi there very nice blog!! Guy .. Beautiful ..
    Wonderful .. I’ll bookmark your web site and take the feeds also?
    I am glad to seek out so many helpful info right here in the post,
    we need work out more strategies on this regard, thanks for sharing.
    . . . . .

  26. glucotrust表示:

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

  27. I’m not that much of a internet reader to be honest
    but your blogs really nice, keep it up! I’ll go ahead and bookmark your site to come back later on. Cheers

  28. Diplomi_vnOl表示:

    купить диплом о среднем образовании в чебоксарах diplomdarom.ru .

發佈留言

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