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,238,734 Responses

  1. BrandonSaisy表示:

    medicine for ed: cheap pharmacy online – viagra without a doctor prescription walmart

  2. You’ll Never Guess This Fob Key Repair’s Benefits Fob key repair

  3. DevonPhack表示:

    http://mexicanpharm24.cheap/# mexican online pharmacies prescription drugs
    men with ed

  4. hilo911表示:

    After exploring a few of the articles on your website,
    I truly like your way of blogging. I book marked it to my bookmark site list and
    will be checking back in the near future. Please check out my website too and tell me what
    you think.

  5. You Are Responsible For The 4 Wheel Mobility Scooter Budget?
    Twelve Top Ways To Spend Your Money handicap 4 wheel scooters

  6. AndrewPhice表示:

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

  7. obsolete表示:

    I am sure this piece of writing has touched all the internet visitors, its really really nice paragraph on building up new website.

  8. 9 Things Your Parents Taught You About Gas Patio Heater Amazon Gas Patio Heater amazon

  9. KevinFiels表示:

    Pill leaflet provided. Latest medicine developments.
    no prescription drugs
    Contraindications explained here. Medication effects explained.

  10. Richardtic表示:

    Профильные трубы – категория металлопроката, которая включает в себя изделия с сечением, отличным от круглого. Ассортимент профильных труб купить металл профильная труба

  11. Jorgeagopy表示:

    india pharmacy: Indian pharmacy international shipping – indian pharmacy

  12. The Most Sour Advice We’ve Ever Been Given About Train Accident Attorney
    Semi truck attorney

  13. always i used to read smaller articles or reviews which also clear their motive,
    and that is also happening with this post which I am reading here.

  14. see this here表示:

    This is nicely put. !

  15. DevonPhack表示:

    https://pharm24.pro/# muse for ed
    supplements for ed

  16. It’s very straightforward to find out any matter on web as compared to textbooks, as I found this piece of writing at this web
    site.

  17. BrandonSaisy表示:

    mexico drug stores pharmacies: mexico pharmacy – mexican border pharmacies shipping to usa

  18. BrandonSaisy表示:

    ed doctor: cheap pharmacy online – best male enhancement

  19. fcb88_ac表示:

    I go to see everyday a few web pages and sites to read articles or reviews, however
    this blog presents feature based posts.

  20. A mesothelioma or asbestos (https://Alford-downs-2.Hubstack.net/) lawyer can help
    victims and their families collect compensation from sources like trust funds, VA
    benefits and personal injury lawsuits.

  21. Buggy 2 In 1表示:

    What’s The Current Job Market For Buggy 2 In 1 Professionals Like?
    Buggy 2 In 1

  22. Please let me know if you’re looking for a article writer for
    your site. You have some really great posts and I believe
    I would be a good asset. If you ever want to take some
    of the load off, I’d love to write some material for your blog in exchange for
    a link back to mine. Please send me an email if interested.
    Regards!

  23. What Is Private Adhd Assessment Uk? What Are The Benefits And How To Utilize It
    how to get assessed for adhd Uk

  24. DevonPhack表示:

    http://pharm24.pro/# viagra without doctor prescription amazon
    best ed solution

  25. See What Automobile Locksmith Near Me Tricks The Celebs Are Utilizing Locksmith Near me

發佈留言

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