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,366,656 Responses

  1. BarryDof表示:

    https://ozempic.art/# buy ozempic

  2. Keitaro и VPS: Обеспечьте себе стабильность и безопасность данных віртуальний сервер для Keitaro

  3. Bookmarks表示:

    Appreciate it for helping out, excellent info.

    Here is my page – Bookmarks

  4. oploverz表示:

    My programmer is trying to persuade me to move to .net from
    PHP. I have always disliked the idea because of the expenses.
    But he’s tryiong none the less. I’ve been using Movable-type on numerous websites for about a year and am anxious about switching to another platform.
    I have heard good things about blogengine.net.
    Is there a way I can transfer all my wordpress posts into it?
    Any kind of help would be greatly appreciated!

  5. LeroyAcuff表示:

    Профессиональный сервисный центр ремонт телефона срочный ремонт сотовых телефонов

  6. Frankevild表示:

    https://ozempic.art/# buy ozempic pills online

  7. Poker online表示:

    Review my web site – Poker online

  8. Captivating and thought-provoking study of the subject.
    Your evaluation was comprehensive and well-informed, delivering readers with a exhaustive appreciation of the primary problems at disposal.

    I shall be delighted to engage extra on this theme.

    If you allow, I would kindly urge you to register with
    me on the SBOBET platform, in which we should continue
    our conversation in a additional participatory arena.

    Here is my website :: Gambling industry

  9. LeroyAcuff表示:

    Профессиональный сервисный центр где можно починить телефон сервисный центр по ремонту телефонов

  10. I like the helpful info you provide in your articles.
    I’ll bookmark your blog and check again here frequently.

    I’m quite sure I’ll learn lots of new stuff right here!
    Best of luck for the next!

    Look at my web blog คาสิโนดีลเลอร์สด

  11. What is New U Life SOMADERM Transdermal Gel.

    Feel free to surf to my web blog: euphoria mushroom gummies

  12. porno表示:

    It’s very effortless to find out any topic on web as compared to books,
    as I found this paragraph at this web site.

  13. Javier McCall表示:

    How To Make A Profitable Repair Window Seal Entrepreneur Even If You’re Not Business-Savvy window seal Repair

  14. Jeremypag表示:

    ozempic coupon ozempic buy cheap ozempic

  15. I drop a leave a response when I like a post on a website
    or I have something to add to the conversation. It’s
    a result of the sincerness communicated in the post I
    looked at. And on this post JS 依照元素出現數量排序 – 馬老師
    雲端研究室. I was actually moved enough to drop a comment :
    ) I do have a couple of questions for you if it’s okay.
    Is it only me or does it give the impression like a few of the remarks come across like they are
    coming from brain dead visitors? 😛 And,
    if you are posting on additional social sites, I’d like to keep up with everything fresh you
    have to post. Could you list all of all your public sites like your twitter feed, Facebook page or linkedin profile?

    my site :: starting daycare

  16. RamonRek表示:

    ozempic online: Ozempic without insurance – ozempic cost

  17. LeroyAcuff表示:

    Профессиональный сервисный центр мастерская по ремонту сотовых телефонов сколько стоит ремонт смартфона

  18. Jeremypag表示:

    rybelsus cost rybelsus pill semaglutide online

  19. Профессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
    Мы предлагаем: ремонт бытовой техники в волгограде
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  20. Mandy Bird表示:

    You’ll Be Unable To Guess 3 Wheel Stroller Lightweight’s Tricks 3 wheel stroller lightweight (images.Google.as)

  21. See What Local Window Repair Tricks The Celebs Are Using Local Window Repair

  22. How To Explain Replacement Car Key Cost To Your
    Grandparents Car keys battery Replacement Near me

  23. 9 . What Your Parents Teach You About L Shaped Couch L shaped couch

  24. Frankevild表示:

    https://rybelsus.shop/# semaglutide online

  25. BarryDof表示:

    https://rybelsus.shop/# semaglutide cost

  26. В магазине сейфов предлагают сейф купить в москве купить сейф оптом

  27. Hayley Bacon表示:

    Sectional Couches For Sale Techniques To Simplify Your Daily Lifethe One Sectional Couches For Sale Trick That Should Be Used By Everyone Be Able To sectional couches for sale (Kai)

發佈留言

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