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,237,933 Responses

  1. Raterphal App表示:

    WOW just what I was looking for. Came here by searching for Raterphal App

  2. I don’t know if it’s just me or if everyone else experiencing issues with your
    blog. It seems like some of the text in your content are running off the screen. Can somebody else please provide feedback and
    let me know if this is happening to them as well?
    This might be a problem with my web browser because I’ve had this happen before.
    Many thanks

  3. CarrollUnton表示:

    deneme bonusu veren siteler denemebonusu2026.com https://matadorbet.bid/# matadorbet bid

  4. Heya i am for the first time here. I came across this board and I to
    find It truly useful & it helped me out a lot. I am hoping
    to give one thing again and help others like you helped me.

  5. ClydePab表示:

    deneme bonusu veren siteler 2024: deneme bonusu veren yeni siteler – deneme bonusu veren siteler

  6. Tony表示:

    9 Lessons Your Parents Teach You About Chiminea Terracotta chiminea terracotta (Tony)

  7. rp8888rp8888表示:

    My brother suggested I might like this website.

    He was totally right. This post truly made my day. You can not imagine just how much time I had spent for this information!
    Thanks!

  8. In Wall Fireplace Tools To Facilitate Your Life Everyday Electric Firesuite

  9. 3 Ways That The Car Key Cut And Program Near Me Influences Your Life
    Remote Key Programming

  10. Diplomi_eber表示:

    купить диплом высшем новосибирск prema365-diploms.ru .

  11. 15 Presents For Those Who Are The Mesothelioma Lawyer Lover In Your Life mesothelioma Attorney

  12. You Are Responsible For The Item Upgrader Budget?
    Twelve Top Ways To Spend Your Money Item Upgrading

  13. Adele表示:

    Pretty nice post. I simply stumbled upon your blog and wanted to mention that I have truly enjoyed browsing your weblog posts.

    After all I’ll be subscribing for your feed and I am hoping
    you write once more soon!

  14. LarryCoell表示:

    matadorbet.bid matadorbet bid matadorbet

  15. Dane表示:

    10 Unexpected Car Key Programmer Near Me Tips auto car
    key programmer near me (Dane)

  16. ai-porn.asia表示:

    I think the admin of this site is genuinely working hard in favor of his site, since here every material is quality based
    data.

  17. An Intermediate Guide On ADHD Private Diagnosis
    London Private Adhd Assessment Edinburgh Cost

  18. Felix表示:

    What’s The Job Market For ADHD Assessment For Adults London Professionals Like?
    adhd assessment for adults london (Felix)

  19. AaronBlupe表示:

    Создание лендингов под ключ в студии в Москве включает проектирование, дизайн и программирование, обеспечивающее эффективность и удобство использования. Также предоставляются услуги: оптимизация для Яндекс и Google, настройка рекламных кампаний, поддержка, обслуживание и ведение маркетинга studiya poddergki ru

  20. Diplomi_yaer表示:

    как купить диплом в нижнем тагиле prema365-diploms.ru .

  21. duct split表示:

    mohajer-co.com
    First of all I would like to say fantastic blog! I had a quick question which I’d like to ask if you don’t mind.
    I was interested to find out how you center yourself and clear your mind prior to writing.
    I’ve had a difficult time clearing my mind in getting my ideas out there.
    I do take pleasure in writing but it just seems like the first 10 to
    15 minutes are generally lost simply just trying to
    figure out how to begin. Any recommendations or hints? Kudos!

  22. Drug information leaflet. Cautions.
    can i order fexofenadine without rx
    Some about medicines. Read information now.

  23. bonek8080表示:

    Capek kalah mulu? Nih cobain situs bonekslot gacor terpercaya dijamin paling gacor tidak ada tandingannya

  24. Guide To Kids Bunk Beds With Storage: The Intermediate Guide To Kids
    Bunk Beds With Storage kids Bunk beds With storage (https://www.metooo.io/)

  25. ClydePab表示:

    slot oyunlar?: slot oyunlar? puf noktalar? – en kazancl? slot oyunlar?

  26. What’s The Job Market For Sofas And Sectionals Professionals?
    sofas and Sectionals

  27. Don’t Buy Into These “Trends” Concerning Double Buggy 3 Wheels best 3 wheel
    stroller With car seat (http://79bo.cc/space-uid-6868692.html)

  28. Gabriele表示:

    The Reasons To Work With This Electric Fire Suites freestanding fireplace suites (Gabriele)

發佈留言

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