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,122,777 Responses

  1. Easydrorbix表示:

    target pharmacy clomid price: people’s pharmacy prozac – online indian pharmacy

  2. Helpful content, Appreciate it!

  3. 5 Killer Quora Answers On Automatic Folding Electric Scooter automatic folding electric
    scooter [http://Lslv168.com/]

  4. 5 Killer Queora Answers On How To Get Diagnosed With ADHD 9326527.xyz
    (http://Www.9326527.xyz)

  5. Easydrorbix表示:

    cialis pharmacy india: humana pharmacy online – online pharmacy store hyderabad

  6. Why Kids Bunk Beds Is Everywhere This Year bunk bed For kids

  7. What’s Taking place i’m new to this, I stumbled upon this I
    have discovered It absolutely useful and it has helped me out loads.
    I am hoping to contribute & help different customers like its aided me.
    Good job.

  8. What Is The Reason? Automatic Folding Mobility Scooter Uk Is Fast Increasing To
    Be The Hot Trend For 2023 Automatic Folding Scooter

  9. Drstobeese表示:

    drug store news ce: does pharmacy sell viagra – pharmacy direct viagra

  10. bokep bocah表示:

    Wonderful post however , I was wondering if you could write a litte more
    on this subject? I’d be very thankful if you could elaborate a little bit
    further. Thank you!

  11. ShakiraLesee表示:

    Я думаю, что Вы не правы. Я уверен. Давайте обсудим это. Пишите мне в PM.
    5. когда вы пересолили бульон, https://www.info-tema.com/ то, в таком случае поместите в него мешочек рисовой крупы. Современные психологи рекомендуют много эффективных способов, помогающих избежать конфликтов с близкими людьми.

  12. Lewis表示:

    10 Unexpected Replacement Porsche Key Tips porsche car key usb
    Lewis,

  13. Cell-Assisted Lipotransfer for Cosmetic Breast Augmentation: Supportive Use of Adipose-Derived Stem/Stromal Cells // Aestehtic Plastic Surgery : journal. Basic Potential of Carbon Nanotubes in Tissue Engineering Applications (англ.

  14. 10 Things You’ve Learned In Preschool That’ll Help You Understand ADHD Tests For Adults am i adhd test (http://www.stes.tyc.edu.tw)

  15. mj-go.kr表示:

    What’s The Current Job Market For Triple Sleeper Bunk Bed
    Professionals? Triple sleeper bunk bed [mj-go.kr]

  16. Thank you for the auspicious writeup. It actually used to be a
    entertainment account it. Glance complicated to far delivered agreeable from you!
    By the way, how can we communicate?

  17. Its such as you learn my thoughts! You appear to grasp so much approximately this, like you
    wrote the ebook in it or something. I think that you could do with some p.c.

    to power the message house a little bit,
    however instead of that, that is fantastic blog.
    A great read. I’ll definitely be back.

  18. You actually expressed it perfectly.

  19. Easydrorbix表示:

    Levitra with Dapoxetine: reputable online pharmacy cialis – cheap scripts pharmacy

  20. You actually explained this really well.

  21. Great forum posts Cheers.

  22. konteyner表示:

    konteyner modelleri | Yazınız, konuya dair oldukça geniş bir bilgi yelpazesi sunmuş. Özellikle altını çizdiğiniz önemli noktalar ve verdiğiniz stratejik tavsiyeler çok değerliydi. Emeğinize sağlık!

  23. You’ll Be Unable To Guess Gspot Sex Toys’s Benefits gspot sex toys

  24. Why viewers still make use of to read news papers when in this technological world everything is accessible on web?

  25. video porno表示:

    you are in point of fact a just right webmaster. The web site
    loading velocity is amazing. It seems that you are doing any distinctive trick.
    Moreover, The contents are masterpiece. you have done a fantastic
    task on this matter!

  26. Why Pod Coffee Machine Could Be Much More Hazardous Than You Think
    coffee pod machine

  27. Anja表示:

    Pretty component of content. I just stumbled upon your web site and in accession capital to assert that I get actually enjoyed account your weblog posts.

    Anyway I’ll be subscribing for your augment and even I success you get
    entry to persistently quickly.

  28. Drstobeese表示:

    Super Kamagra: publix pharmacy augmentin – bystolic pharmacy

發佈留言

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