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,251,896 Responses

  1. scam表示:

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

  2. вывод из запоя на дому ростов-на-дону http://www.avtomobili.creartuforo.com/viewtopic.php?id=730 .

  3. Nikefut表示:

    dark web access dark market 2024 darkmarket

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

  5. Thanks for the auspicious writeup. It in truth was once a leisure account it.
    Look advanced to far added agreeable from you! However, how can we be in contact?

  6. BrandenSlomy表示:

    priligy: priligy maxpharm – cheap priligy

  7. What’s up friends, its impressive piece of writing concerning teachingand entirely explained, keep it up all the time.

  8. Dereketerm表示:

    buy amoxicillin online no prescription: cheap amoxil – where to buy amoxicillin 500mg without prescription

  9. Introduction Glyco Balance Blood Sugar is a dietary supplement designed to support healthy blood
    sugar levels in individuals with diabetes and prediabetes.

  10. Узнай все о варикоцеле у мужчин симптомы варикоцеле яичка у мужчины

  11. 10 Reasons Why People Hate Trucking Attorneys Near Me trucking accident Attorney near me

  12. Hi there! This blog post could not be written any better!

    Going through this post reminds me of my previous roommate!

    He always kept talking about this. I will forward this article to him.
    Pretty sure he’s going to have a great read. Thanks for sharing!

  13. Bradleygoath表示:

    can i order prednisone prednisone ray pharm buy prednisone online australia

  14. Тут можно преобрести сейф для оружия купить сейф для оружия купить в москве

  15. Darlene表示:

    Five Best Full Size Bunk Beds Projects To Use For Any Budget bunk bed uk – Darlene

  16. BrandenSlomy表示:

    prednisone 1 mg daily: prednisoneraypharm – prednisone online australia

  17. Узнай все о варикоцеле 1 степени варикоцеле у мужчин

  18. You’ll Never Guess This Automatic Folding Mobility Scooter
    Reviews’s Tricks automatic folding mobility scooter reviews

  19. I enjoy looking through a post that can make people think.
    Also, thanks for allowing for me to comment!

  20. This Is The Myths And Facts Behind Car Lawyer Near Me car crash Lawyer near me

  21. What’s Holding Back In The Cost For Spare Car Key Industry?
    car key cloning cost

  22. Have you ever thought about including a little bit more
    than just your articles? I mean, what you say
    is fundamental and all. However think about if you added some great
    pictures or videos to give your posts more, “pop”! Your content is excellent but with pics and
    videos, this blog could certainly be one of the most beneficial in its field.
    Superb blog!

  23. Thank you, I have just been looking for info approximately this topic for
    ages and yours is the greatest I have came upon till now. But, what in regards to the bottom line?
    Are you sure in regards to the source?

  24. The other day, while I was at work, my sister stole my
    iphone and tested to see if it can survive a thirty foot drop, just so she can be a youtube sensation. My iPad is now
    broken and she has 83 views. I know this is totally
    off topic but I had to share it with someone!

  25. No matter if some one searches for his essential thing, so he/she desires to be available that
    in detail, so that thing is maintained over here.

  26. Узнай все о заболевание варикоцеле признаки варикоцеле

  27. discuss表示:

    My relatives all the time say that I am killing my time here at web, but I know I am getting know-how daily by reading thes fastidious posts.

發佈留言

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