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,521,444 Responses

  1. slot gacor表示:

    Wow, this post is fastidious, my younger sister is analyzing these
    kinds of things, therefore I am going to tell her.

  2. 12 Companies Leading The Way In How To Check The
    Authenticity Of Pragmatic 프라그마틱 플레이

  3. mystery Boxes表示:

    The 10 Most Terrifying Things About Online Mystery Boxes mystery Boxes

  4. Hey There. I discovered your weblog the use
    of msn. This is a really neatly written article.
    I will be sure to bookmark it and come back to learn more of your helpful info.
    Thanks for the post. I will certainly return.

  5. The 3 Greatest Moments In Mystery Box History Mystery Box Opener

  6. Paul表示:

    Guide To Mixed Anxiety Disorder: The Intermediate Guide The Steps To Mixed Anxiety Disorder mixed anxiety disorder (Paul)

  7. rust cheats表示:

    Hey I know this is off topic but I was wondering if you knew
    of any widgets I could add to my blog that automatically
    tweet my newest twitter updates. I’ve been looking for a plug-in like this for quite some time and was hoping maybe you would have
    some experience with something like this. Please let me know if
    you run into anything. I truly enjoy reading your blog
    and I look forward to your new updates.

  8. r7 casino表示:

    Для всех слотов предусмотрен удобный демонстрационный режим, аналогичный основной версии игры.

  9. slot表示:

    This excellent website certainly has all the information and facts
    I needed about this subject and didn’t know who to ask.

  10. Williamagric表示:

    best pills for ed http://pharm24.pro/# buy drug online

  11. Twyla表示:

    5 Killer Quora Answers To Compact Single Stroller compact single stroller – Twyla

  12. How To Beat Your Boss With Christopher Treehouse Bed Indoor treehouse Bed (https://lindahl-malone-2.technetbloggers.de/)

  13. 9 Lessons Your Parents Taught You About Stroller 2 In 1 Car Seat stroller 2 In 1

  14. BrandonSaisy表示:

    mexico pharmacies prescription drugs: mexico pharmacy – buying from online mexican pharmacy

  15. AwbHesia表示:

    to get educated withBuy direct from our online pharmacy. Your levitra coupons at the lowest prices anywhere on the net offered on this site

  16. post482638表示:

    Hey very spectacular blog!! Fellow .. Spectacular .. Amazing .. I will bookmark your blog and take the feeds additionally�I’m delighted to locate so numerous advantageous information here in the post, we want increase more procedures on this regard, thank you for distribution.

    Feel free to visit my web page: http://www.Adtgamer.com.br/showthread.php?p=482638

  17. 5 Reasons To Be An Online Locked Car And 5 Reasons
    Why You Shouldn’t Locked Car Keys In Car (https://Mail.Swgtf.Com)

  18. Diplomi_thkl表示:

    купить диплом о высшем образовании в курске server-diploms.ru .

  19. See What Electric Outdoor Heaters For Patio Tricks The Celebs
    Are Making Use Of Electric outdoor heaters For patio

  20. I seriously love your site.. Great colors & theme. Did you create this website yourself?
    Please reply back as I’m attempting to create my own site and want to learn where you got this from or just what the theme is named.
    Thank you!

  21. Diplomi_qikl表示:

    купить диплом в комсомольске-на-амуре server-diploms.ru .

  22. LeroyBak表示:

    mexican border pharmacies shipping to usa mexican pharmacy reputable mexican pharmacies online

  23. Jocelyn表示:

    14 Creative Ways To Spend On Leftover Upvc Patio Doors Budget upvc back doors – Jocelyn

  24. What’s The Job Market For How Much Fabric For 2 Seater Sofa Professionals?
    How Much Fabric For 2 Seater Sofa (Bbs.0817Ch.Com)

  25. Williamagric表示:

    natural cures for ed http://pharm24.pro/# ed in men

  26. Vulkan KZ表示:

    Теперь можно побывать в виртуальном мире, позабыв на
    время о реальном.

  27. There are various tools and websites that claim to permit users
    to view private Instagram profiles, but it’s important to open these following caution. Many of these tools can be unreliable,
    may require personal information, or could violate Instagram’s terms
    of service. Additionally, using such tools can compromise your own security or lead to scams.
    The safest and most ethical pretension to view a private profile is to send a follow request
    directly to the user. Always prioritize privacy and worship in your online interactions.

    my website :: injectbox private instagram viewer

  28. cut表示:

    The Top Ford Replacement Key Cost Uk The Gurus Are Using 3 Things cut

發佈留言

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