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,239,038 Responses

  1. Much appreciated! I recognize this update on the latest
    vape law news!

  2. Touche. Sound arguments. Keep up the amazing spirit.

  3. You ought to take part in a contest for one of the most useful blogs on the web.
    I’m going to recommend this blog!

  4. timspadTef表示:

    Вы абсолютно правы. В этом что-то есть и идея отличная, поддерживаю.
    ржд онлайн билет разноплановые и по своему целевому содержанию, и видам активности. Традиционный морской релаксация всегда в тренде.

  5. LeroyBak表示:

    mexico drug stores pharmacies mexico pharmacy reputable mexican pharmacies online

  6. The 15 Things Your Boss Wants You To Know About Electric Fire
    Place Suite You’d Known About Electric Fire Place Suite large electric fireplace suites

  7. Guide To Sectional U Shaped Couch: The Intermediate Guide Towards Sectional U Shaped
    Couch sectional U shaped couch

  8. What’s up, its nice post on the topic of media print, we all
    be aware of media is a fantastic source of data.

    https://ww9.duta4d.cc/

  9. Jorgeagopy表示:

    online ed drugs: buy drugs – erectyle dysfunction

  10. DevonPhack表示:

    https://indianpharm24.pro/# world pharmacy india
    best way to treat ed

  11. LeroyBak表示:

    indianpharmacy com India pharmacy international online pharmacy india

  12. 7 Simple Secrets To Totally Intoxicating Your French Style Fridge Freezer Plumbed French Door Refrigerator With Largest Freezer

  13. The vital figures and scenes are positioned in further quadrilateral settings of mosaic-like decoration, dominated by purple and blue colors.

  14. event表示:

    Amazing blog! Do you have any helpful hints for aspiring
    writers? I’m hoping to start my own site soon but I’m a little lost on everything.
    Would you suggest starting with a free platform
    like WordPress or go for a paid option? There
    are so many options out there that I’m completely overwhelmed ..

    Any tips? Many thanks!

    Look at my page :: event

  15. buy cgild porn instagram best services.

  16. Williamagric表示:

    erectial dysfunction https://mexicanpharm24.cheap/# mexican drugstore online

  17. Jorgeagopy表示:

    india pharmacy: India pharmacy delivery – reputable indian online pharmacy

  18. Williamagric表示:

    how to overcome ed naturally https://mexicanpharm24.cheap/# medication from mexico pharmacy

  19. Jorgeagopy表示:

    reputable indian online pharmacy: Best Indian pharmacy – pharmacy website india

  20. ArthurReile表示:

    Фабрика кашеварных гарнитуров в Санкт-петербурге – это ваш надежный партнер в течение произведении кашеварных интерьеров. Мы специализируемся на исследованию, производстве равным образом установке высококачественных кашеварных гарнитуров, которые соединяют в течение себе стиль, функциональность равным образом долговечность. Наша предназначение – выдать клиентам личные ответы, сделанные начиная с. ant. до учётом их пожеланий а также необходимостей, чтоб любил шакша стала приятным и удобным местом для бытие а также творчества https://www.tivokya0kuhnishki.ru.

  21. srasurvivor表示:

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

  22. Five Killer Quora Answers To Glass Doctor Near Me Glass Doctor Near Me

  23. LeroyBak表示:

    mexican mail order pharmacies mexican pharmacy buying prescription drugs in mexico online

  24. Medicines information leaflet. What side effects can this medication cause?
    why would a doctor prescribe metformin
    All trends of medicines. Get here.

  25. id=”firstHeading” class=”firstHeading mw-first-heading”>Search results

    Hеlp

    Engloish

    Tools

    Tools
    moѵe to sidebar hide

    Actions

    Ԍeneral

    Τake a look aat my hߋmepage :: ซื้อเว็บสล็อต

  26. William表示:

    Are You Responsible For A Mesothelioma And Asbestosis Budget?
    12 Tips On How To Spend Your Money mesothelioma lawsuit (William)

發佈留言

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