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,522,649 Responses

  1. Jorgeagopy表示:

    pharmacy website india: Indian pharmacy international shipping – indian pharmacy paypal

  2. Sex Tre con表示:

    I’d like to find out more? I’d love to find out some additional information.

  3. Please let me know if you’re looking for a article author for your weblog.
    You have some really great articles and I think I would be a good asset.

    If you ever want to take some of the load off, I’d absolutely love to write some articles for your blog in exchange
    for a link back to mine. Please send me an e-mail if interested.

    Cheers!

    my webpage :: https://www.cucumber7.com/

  4. Jorgeagopy表示:

    mexico pharmacies prescription drugs: mexican pharm 24 – purple pharmacy mexico price list

  5. LeroyBak表示:

    best india pharmacy medicines from India pharmacy website india

  6. Pills prescribing information. What side effects can this medication cause?
    can i buy cheap phenytoin without prescription
    Actual trends of medication. Read information now.

  7. hello!,I like your writing so much! proportion we keep up a correspondence extra about your article on AOL?
    I require an expert in this space to resolve my problem. Maybe that is you!
    Taking a look forward to see you.

  8. Find Out More表示:

    My brother recommended I might like this web site.
    He was totally right. This submit actually made my day.
    You cann’t consider simply how so much time
    I had spent for this info! Thanks!

  9. Wow that was odd. I just wrote an very long comment but after I
    clicked submit my comment didn’t show up. Grrrr… well I’m not writing all that
    over again. Anyhow, just wanted to say wonderful blog!

  10. How To Explain Best Auto Accident Lawyers To Your Boss Car Injury Attorneys

  11. LeroyBak表示:

    best india pharmacy India pharmacy international online pharmacy india

  12. Trefuaa表示:

    Полезные советы по покупке диплома о высшем образовании без риска

    jivonews.ru/bezopasnaya-pokupka-diploma-s-vneseniem-v-bazu

  13. A Productive Rant About Car Key Cuts spare car Keys

  14. LeroyBak表示:

    best ed treatment cheap meds buying ed pills online

  15. When someone writes an post he/she retains
    the idea of a user in his/her brain that how a user can understand it.
    So that’s why this article is outstdanding.

    Thanks!

  16. Treftbb表示:

    Как получить диплом техникума официально и без лишних проблем
    share.psiterror.ru/2024/10/14/gde-mozhno-kupit-podlinnyy-diplom-onlayn.html

  17. Jorgeagopy表示:

    drugs for ed: cheap drugs online – drug prices

  18. Trefmyv表示:

    Официальная покупка школьного аттестата с упрощенным обучением в Москве
    kawaa.drake.free.fr/index.php?file=Forum&page=viewtopic&forum_id=1&thread_id=6114

  19. WngPaish表示:

    Be smart enough. Read viagra london pharmacy and fast delivery every time you buy here

  20. Lonnie表示:

    20 Trailblazers Are Leading The Way In Wall Mount Fireplace electric fire on wall (Lonnie)

  21. Gary表示:

    What You Should Be Focusing On Improving Treadmills For Sale treadmills for sale near me,
    Gary,

  22. Trefqfq表示:

    Приобретение диплома ПТУ с сокращенной программой обучения в Москве

    buldingnews.ru/kak-vyibrat-nadezhnogo-prodavtsa-diplomov

  23. PORN表示:

    I am really loving the theme/design of your web site.
    Do you ever run into any internet browser compatibility issues?
    A few of my blog visitors have complained about my site not
    working correctly in Explorer but looks great in Firefox.
    Do you have any advice to help fix this issue?

  24. Excellent, what a blog it is! This weblog presents helpful information to us, keep it up.

    Feel free to surf to my webpage แทงหวยเวียดนาม

  25. Five Killer Quora Answers On Case Opening Battle case opening battle (articlescad.com)

  26. Carlton表示:

    The Reason Why Fiat Replacement Key Is The Obsession Of Everyone In 2023 fiat punto remote
    key replacement (Carlton)

  27. Rodney表示:

    5 Lessons You Can Learn From Walking Pad Under Desk walking desk treadmill (Rodney)

  28. LeroyBak表示:

    best ed medications cheap pharmacy online medicine for ed

  29. This Is The Ultimate Cheat Sheet For Sofa Couch L Shape l shape sofa
    with Recliner; sofas02517.Wikiannouncement.com,

發佈留言

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