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,228,074 Responses

  1. Darrelherse表示:

    en iyi slot siteleri: casino slot siteleri – slot siteleri guvenilir

  2. Bunk bed Uk表示:

    10 Things Everybody Hates About Best Low Bunk Beds Bunk bed Uk

  3. 步歩違い表示:

    Again in prehistoric times, when eating was all about survival, it made sense for your brain to reward you for in search of out excessive-caloric foods.

  4. The Federal CIO Council commissioned a study of the $100 million IT security investment for the Department of Veterans Affairs with results shown quantitatively.

  5. 匿名訪客表示:

    Ahaa, its nice discussion regarding this post at this place at this webpage,
    I have read all that, so at this time me also commenting at this place.

  6. sungchol.org表示:

    You’ll Never Guess This Why Does My Volkswagen Say No
    Key’s Tricks why does my volkswagen say no key; sungchol.org,

  7. Darrelherse表示:

    slot casino siteleri: guvenilir slot siteleri 2024 – deneme bonusu veren slot siteleri

  8. Blingle Jacksonville, FL
    10221-3 Beasch Boulevard,
    Jacksonville, FL 32246, United Ѕtates
    9049778928
    Creative outdoor light setups

  9. Medicine information sheet. What side effects?
    cost of cheap levaquin prices
    Actual news about drugs. Read now.

  10. Steering clear of Internet sites affected with malware is actually crucial for sustaining unit health and wellness. Routine scans can easily aid ensure you are actually certainly not endangered by Websites contaminated with malware.

  11. Great blog here! Also your web site loads up very fast!
    What web host are you using? Can I get your affiliate link to
    your host? I wish my website loaded up as fast as yours lol

  12. guru traffic表示:

    Excellent items from you, man. I have bear in mind your stuff prior to
    and you are just extremely wonderful. I actually like what you’ve obtained right here, certainly like what you’re
    saying and the best way wherein you assert it.

    You make it entertaining and you still take care of to keep it sensible.
    I can’t wait to read much more from you. That is actually a great web
    site.

  13. KevinSounc表示:

    https://sweetbonanza.network/# sweet bonanza guncel

  14. Mazryws表示:

    Пошаговая инструкция по официальной покупке диплома о высшем образовании

    diplomasx.com

  15. KevinSounc表示:

    http://slotsiteleri.bid/# deneme bonusu veren siteler

  16. KevinSounc表示:

    http://sweetbonanza.network/# sweet bonanza slot demo

  17. Ev Taşıma | Taşınma sürecinde karşılaşılan zorlukları minimize etmek için profesyonel bir firma ile çalışmanın önemini vurgulayan bu makale, müşterilerimiz için çok faydalı olacaktır. Kozcuoğlu Ev Taşıma olarak, bu konuda en iyi hizmeti sunuyoruz.

  18. child porn表示:

    This is a topic which is near to my heart… Thank you! Exactly where
    are your contact details though?

  19. With standard tooling methods often being so labor-intensive, Mantle 3D’s approach looks like it could change industry
    standards for production efficiency.

    I’m interested about how Mantle’s 3D technology manages adjustments or
    iterations during the production phase.

    I’m interested about how Mantle 3D deals with the challenges of integrating
    cooling channels and other complex features into
    injection molds.

  20. If you are going for finest contents like me, just go to see this website daily since it provides feature contents,
    thanks

  21. Что такое расстановки по Хеллингеру и в чем их суть. https://rasstanovkiural.ru

  22. This paragraph offers clear idea for the new users of blogging, that really
    how to do running a blog.

  23. Glycogen is a crucial energy reserve stored primarily in the liver and muscles, ready to
    be converted into glucose when needed to fuel your body during exercise or prolonged physical activity.

  24. visit here表示:

    Thanks , I’ve just been searching for information about this topic for a while and yours is the
    best I’ve found out so far. But, what concerning the conclusion? Are you positive in regards to the supply?

  25. Hmm is anyone else experiencing problems with the images on this blog loading?
    I’m trying to find out if its a problem on my end or if it’s the
    blog. Any responses would be greatly appreciated.

發佈留言

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