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,229,751 Responses

  1. LarryCoell表示:

    matadorbet matadorbet.bid matadorbet giris

  2. Concetta表示:

    The 10 Worst French Door Fridge And Freezer
    Mistakes Of All Time Could Have Been Prevented french door fridge or side by side – Concetta

  3. Medicament prescribing information. Generic Name.
    can you buy paxil without a prescription
    Everything what you want to know about pills. Read now.

  4. 7 Small Changes That Will Make The Difference With Your Velvet Chesterfield
    Sofa modern chesterfield leather sofa

  5. The Most Advanced Guide To Compact Stroller travel pram – cementpeak3.Bravejournal.net

  6. I was recommended this web site by way of my cousin. I’m not certain whether or not this put up is written through him as
    nobody else recognise such designated approximately my trouble.
    You’re wonderful! Thank you!

  7. ThePokies 104表示:

    Wow, this post is fastidious, my sister is analyzing these things, therefore
    I am going to convey her.

  8. Nikefut表示:

    darknet site darknet markets dark web market

  9. Hmm is anyone else encountering problems with
    the images on this blog loading? I’m trying to determine if its a problem on my end or if it’s the blog.
    Any responses would be greatly appreciated.

  10. What Experts From The Field Of Kia Key Fob Want You To Be Able To kia dealer Replacement key

  11. The No. One Question That Everyone Working In Sleeping Couch And Sofa Needs To Know How To Answer leather sleeper sofa (images.google.ms)

  12. WordPress GPL Themes / GPL Plugins The most complete cracking plugin/theme store on the market, with a total website of nearly 20000+ Ensure that the product has no backdoors and is safe to use Search for the desired products directly in English. The English search should be purposeful

  13. I couldn’t refrain from commenting. Perfectly written!

    Look at my homepage Randm Tornado 9000

  14. Тут можно преобрести сейф огнестойкий огнестойкий сейф купить

  15. Тут можно преобрести шкаф для ружья сейф оружейный цена

  16. 10 Life Lessons We Can Learn From Double Glazing Repair Bedford storefront window Glass repair

  17. nuddies表示:

    Hey! I’m at work browsing your blog from my new iphone
    4! Just wanted to say I love reading through your blog and look forward to all your posts!

    Carry on the great work!

  18. ScottAtora表示:

    В настоящее время одной из ключевых современных информационных угроз для общества в сфере медиабезопасности становится вовлечение детей и подростков в деструктивные Интернет-сообщества секс дп слив молодые школьниц

  19. Thepokies表示:

    Hi there to every body, it’s my first go to see of this
    web site; this web site contains awesome and really fine stuff for visitors.

  20. ClydePab表示:

    ultrabet giris: ultrabet bonus – ultrabet bonus

  21. It’s hard to come by well-informed people about this topic, however, you
    seem like you know what you’re talking about!
    Thanks

  22. Тут можно преобрести оружейный шкаф цена оружейный сейф купить москва

  23. Derekfar表示:

    ultrabet yeni giris 1125: ultrabet tr online – ultrabet yeni giris 1125

  24. Five People You Should Know In The Green Coffee Beans Industry top rated coffee beans

  25. Nikefut表示:

    dark market dark market list darknet drugs

  26. LarryCoell表示:

    deneme bonusu veren yeni siteler deneme bonusu veren siteler deneme bonusu veren siteler yerliarama.org

  27. CurtisBriff表示:

    SEO Agency
    seo agency near me
    In the vast and boundless realm of the digital cosmos, where every business, great or modest, doth strive for recognition amidst the celestial constellations of the internet, there exists a beacon—a company of noble purpose and profound wisdom. This is the tale of such an enterprise, an SEO company that, like a masterful alchemist, transmutes the ordinary into the extraordinary, guiding both small ventures and mighty corporations toward the zenith of their potential.
    SEO for Your Business
    Imagine, if you will, a humble merchant, whose wares, though crafted with utmost care and unparalleled quality, remain unseen by the wandering eyes of the multitude. Beside him stands a titan of industry, whose name echoes through the corridors of commerce, yet seeks to ascend even higher, to realms unexplored. Both stand upon the shores of the vast digital sea, gazing toward the horizon, yearning for a guide to navigate the treacherous waters that lie ahead.

    Enter the SEO company, a sage of the digital age, whose knowledge penetrates the very fabric of the internet’s intricate tapestry. With wisdom gleaned from years of toil and triumph, they approach the merchant and the titan alike, offering not mere services, but a partnership forged in mutual aspiration.

發佈留言

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