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,478,399 Responses

  1. Wow that was unusual. I just wrote an really long comment
    but after I clicked submit my comment didn’t appear. Grrrr…
    well I’m not writing all that over again. Anyhow, just
    wanted to say excellent blog!

  2. What Is How Anxiety Is Treated And Why Is Everyone Speakin’
    About It? natural anti anxiety Treatment

  3. BrandonJer表示:

    buying prescription drugs in mexico mexico drug stores pharmacies mexican online pharmacies prescription drugs

  4. 15 Reasons Not To Overlook Toto4d Toto Online Terbaik

  5. Mostbet BR表示:

    Howdy! I know this is somewhat off topic but I was wondering if you knew where I could locate a captcha plugin for
    my comment form? I’m using the same blog platform as yours and I’m having problems finding one?
    Thanks a lot!

    My web page :: Mostbet BR

  6. AgustinBougs表示:

    http://mexicanpharm24.pro/# mexico pharmacies prescription drugs
    reputable indian online pharmacy

  7. What’s up Dear, are you in fact visiting this web site on a regular basis, if so afterward you will definitely take fastidious knowledge.

  8. Godfather789表示:

    Godfather789ยเว็บตรงของคนไทย เจ้าพ่อมาเฟียเว็บใหญ่ไม่มีโกง

  9. Very rapidly this web page will be famous among all blog visitors,
    due to it’s fastidious content

    my web page – Erotikanzeigen

  10. BrandonJer表示:

    erection pills viagra online ways to treat erectile dysfunction 100mg viagra without a doctor prescription

  11. Noel Dillion表示:

    Are You Responsible For The Electric Rollator Walker Budget?12 Top Ways To Spend Your Money designer rollator

  12. Wikimapia.org表示:

    One Key Trick Everybody Should Know The One Asbestos Attorneys Near Me Trick Every Person Should Know asbestos lawyer – Wikimapia.org

  13. AgustinBougs表示:

    https://drugs24.pro/# ed solutions
    mail order pharmacy india

  14. What’s The Current Job Market For Rolls Royce Replacement Key Professionals?

    rolls royce replacement key [jasontrout1.bravejournal.net]

  15. 10 Meetups On Window Hinge Repair You Should Attend double glazing hinge Repairs near me

  16. At this moment I am going away to do my breakfast, afterward having my breakfast coming again to
    read further news.

  17. Essie Arndell表示:

    The Reasons Anxiety Symptoms Lump In Throat Isn’t As Easy As You Imagine Anxiety Symptoms Headache

  18. 1 win casino表示:

    Everything is very open with a very clear description of the
    issues. It was truly informative. Your site is very useful.

    Thank you for sharing!

  19. star911表示:

    Outstanding story there. What occurred after? Take care!

  20. Kirby Trumble表示:

    Five Killer Quora Answers On Private ADHD Assessment London private adhd assessment london

  21. Elma Mahn表示:

    Why Private ADHD Assessment Is The Right Choice For You?Private adhd Assessment kent

  22. BrandonJer表示:

    vacuum pumps for ed canadian drugs prescription drugs

  23. BrandonJer表示:

    cheapest online pharmacy india top 10 pharmacies in india india pharmacy mail order

  24. Sazrdrp表示:

    Всё, что нужно знать о покупке аттестата о среднем образовании без рисков
    landik-diploms.ru

  25. Профессиональный сервисный центр по ремонту сотовых телефонов в Москве.
    Мы предлагаем: ремонт ультрабуков мастер
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  26. See What Replacement Car Key Audi Tricks The Celebs Are Using replacement car key
    audi (https://images.google.com.gt)

  27. 15 Secretly Funny People Working In Skoda Fabia Key Replacement Skoda keys (https://hvass-riis.blogbright.net/)

  28. near Me表示:

    Indisputable Proof You Need Porsche Key Battery near Me

  29. AgustinBougs表示:

    http://indianpharmdelivery.com/# indian pharmacy
    buy medicines online in india

發佈留言

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