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,370,355 Responses

  1. StevenNub表示:

    amoxicillin canada price: Amoxicillin buy online – amoxicillin 500 mg brand name

  2. Dereketerm表示:

    priligy maxpharm: buy priligy max pharm – Priligy tablets

  3. This information is priceless. When can I find out more?

  4. Video indir表示:

    Kanuna aykırı ve izinsiz olarak kopyalanamaz, başka yerde yayınlanamaz.

  5. slot gacor表示:

    Your way of describing everything in this paragraph is
    actually good, every one be capable of without difficulty know it, Thanks a lot.

  6. Bezomealved表示:

    Детям нужно было купить зимнюю одежду, а денег не хватало. Подруга рассказала про Telegram-канал Займы без отказа на карту. Там оказалось все так просто: отправляешь заявки сразу в несколько компаний, и тебе 100% одобряют. Деньги пришли быстро, смогла купить детям все, что нужно. Теперь точно знаю, куда обращаться в экстренных ситуациях.

  7. It is really a nice and helpful piece of information. I’m happy that you just
    shared this useful info with us. Please stay us informed like this.

    Thank you for sharing.

  8. Medicament information sheet. Brand names.
    can i purchase cheap ramipril for sale
    Some about medicament. Read information here.

  9. Nikefut表示:

    tor dark web dark website https://darknetmarketstore.com/ – darkmarket list

  10. Odell Goforth表示:

    Nice post. I learn something new and challenging on sites I stumbleupon on a daily basis.
    It’s always useful to read content from other authors and practice something from other websites.

  11. BrandenSlomy表示:

    amoxicillin 500 coupon: amoxil – buy amoxicillin 500mg canada

  12. Hurrah! After all I got a webpage from where I know how to genuinely obtain useful facts regarding my study
    and knowledge.

  13. RPRP AI表示:

    Hi there, always i used to check web site posts here in the early hours
    in the daylight, because i enjoy to gain knowledge of more and more.

  14. Wonderful article! We will be linking to this particularly great post on our website.
    Keep up the great writing.

  15. BrandenSlomy表示:

    clomid medication: cheap clomid – can i buy generic clomid no prescription

  16. BrandenSlomy表示:

    how to buy amoxycillin: amoxil – cost of amoxicillin

  17. Nikefut表示:

    how to get on dark web tor markets links https://darknetmarketstore.com/ – dark web market

  18. LeonardKnism表示:

    кухни санкт петербург — Широкий выбор кухонь в Санкт-Петербурге на заказ.

  19. This website certainly has all of the info I wanted concerning this subject and didn’t
    know who to ask.

  20. As interpretacoes dos sonhos mais populares dos livros mais populares sobre o sono
    Num sonho, apanhar coisas

    [url=http://park1.wakwak.com/%7earaki/cgi-bin/yybbs/yybbs.cgi?list=thread]Sonha com um cao que morde o seu braco? Doeu e sangrou? Interpretacao de um sonho de acordo com diferentes livros de sonho[/url] [url=http://www.compassoilfield.com/product/electric-cars-charging-station-new/#comment-342327]Num sonho, apanhar coisas[/url] [url=https://crossoceantravel.com/how-to-travel-with-paper-map/#comment-33401]Num sonho, apanhar coisas[/url] [url=http://earthmilk.co/what-are-the-best-beverages/#comment-494952]Porque e que sonho com uma cruz partida?[/url] [url=http://joomla-461471-1470402.cloudwaysapps.com/blog/item/25-tired]Sonho de loja de penhores[/url] 983f1fa

  21. BrandenSlomy表示:

    cost of cheap clomid pills: clomid online – where buy clomid prices

  22. Hi, constantly i used to check web site posts
    here early in the dawn, as i love to find out more and more.

  23. StevenNub表示:

    cheap amoxicillin 500mg: amoxicillin online pharmacy – amoxicillin online no prescription

  24. вызов нарколога на дом круглосуточно setter.borda.ru/?1-7-0-00000673-000-0-0-1730729894 .

  25. Wayne表示:

    Definitely believe that which you said. Your favorite justification seemed to be on the net the
    easiest thing to be aware of. I say to you, I definitely get
    irked while people think about worries that they just do not know about.
    You managed to hit the nail upon the top as well
    as defined out the whole thing without having side effect , people could
    take a signal. Will probably be back to
    get more. Thanks http://www.Die-seite.com/index.php?a=stats&u=dacia75k6654

發佈留言

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