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,246,526 Responses

  1. DarrenUnjuh表示:

    https://lisinopril1st.com/# buy Lisinopril online

  2. Sazrkje表示:

    Полезные советы по безопасной покупке диплома о высшем образовании
    gadjetforyou.ru/kupit-diplom-byistryiy-put-k-uspehu-v-karere

  3. Kolyaska_bfPl表示:

    Bugaboo: комфорт и безопасность в каждой детали, Купить коляску Bugaboo – значит сделать правильный выбор, Почему мамы выбирают коляски Bugaboo, Комфорт и удобство с Bugaboo, Bugaboo – это качество и надежность, Bugaboo Fox: лучший выбор для активных родителей, Bugaboo Donkey: простор для ваших малышей, Bugaboo Buffalo: коляска для любых приключений.
    bugaboo ant коляска bugaboo ant коляска .

  4. Kolyaska_ltPl表示:

    Почему Bugaboo – лучший выбор для малыша, Bugaboo: лучшее решение для малыша и родителей, Bugaboo: доверие мам по всему миру, Комфорт и удобство с Bugaboo, Bugaboo: легкость и управляемость в каждом краше, Какая коляска Bugaboo подойдет вашей семье, Bugaboo Ant: компактность и функциональность в одном, Bugaboo Runner: коляска для активных мам.
    бугабу для погодок бугабу для погодок .

  5. Learn About Seat Keys Replacement While Working From At
    Home seat ibiza replacement key fob

  6. DarrenUnjuh表示:

    http://cytpremium.com/# buy cytotec online fast delivery

  7. BernardMop表示:

    buy Lisinopril online lisinopril1st Lisinopril 1st

  8. Many thanks, Lots of data!

  9. This site truly has all the info I needed concerning this subject
    and didn’t know who to ask.

    Look into my web page; เครดิตฟรีล่าสุด

  10. Blakesmema表示:

    кухни на заказ — Разработка уникальных кухонь с учетом ваших пожеланий.

  11. Thank you for the auspicious writeup. It in fact was a amusement account it.
    Look advanced to more added agreeable from you!
    By the way, how can we communicate?

  12. BrandenSlomy表示:

    amoxicillin capsules 250mg: com pharm – amoxicillin capsule 500mg price

  13. BrandenSlomy表示:

    buy amoxicillin from canada: buy amoxil online – amoxicillin online without prescription

  14. Yakuza 77表示:

    Excellent goods from you, man. I have understand
    your stuff previous to and you’re just too wonderful. I actually like what you have acquired here, really
    like what you are stating and the way in which you
    say it. You make it enjoyable and you still care for to keep
    it sensible. I can not wait to read far more from you. This is actually a tremendous site.

  15. Buku Mimpi 3D表示:

    Hmm it appears like your website ate my first comment (it was
    extremely long) so I guess I’ll just sum it up what I wrote and say, I’m thoroughly enjoying your blog.
    I too am an aspiring blog blogger but I’m still new to everything.
    Do you have any suggestions for newbie blog writers?
    I’d really appreciate it.

  16. DarrenUnjuh表示:

    https://cytpremium.com/# cytotec pills buy online

  17. Sazrfxo表示:

    Как получить диплом о среднем образовании в Москве и других городах

    sud77.ru/forum/index.php?topic=103214.0

  18. Sazrmqp表示:

    Узнайте, как приобрести диплом о высшем образовании без рисков

    1001viktorina.ru/forum/viewtopic.php?f=19&t=1763&sid=3e6bed299505660e1fea110fe1903591

  19. BrandenSlomy表示:

    cheap clomid without a prescription: how to get cheap clomid online – cost of cheap clomid no prescription

  20. Quality posts is the main to invite the users to go
    to see the web page, that’s what this website is providing.

  21. If you desire to grow your familiarity just keep visiting this web page and be
    updated with the newest news update posted here.

  22. HiOP表示:

    Pub Crawl HiOP

  23. Pills prescribing information. Effects of Drug Abuse.
    can i purchase generic ipratropium no prescription
    Some about medicines. Get now.

  24. BrandenSlomy表示:

    can you buy prednisone online uk: raypharm – prednisone 10 mg tablet

發佈留言

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