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,246,313 Responses

  1. AlbertDuM表示:

    ivermectin 6 mg tablets: price of ivermectin tablets – ivermectin 50

  2. You could definitely see your expertise within the article you
    write. The world hopes for more passionate writers like you who
    are not afraid to mention how they believe. At all times follow your
    heart.

  3. BernardMop表示:

    minocycline 100mg tablets cheapest Ivermectin ivermectin 0.5% lotion

  4. Sazrnpt表示:

    Пошаговая инструкция по официальной покупке диплома о высшем образовании
    cslregister.com/forum/member.php?u=6225

  5. DarrenUnjuh表示:

    https://lisinopril1st.com/# buy Lisinopril 1st

  6. Howdy! Do you know if they make any plugins to help with Search
    Engine Optimization? I’m trying to get my blog to rank for some targeted keywords
    but I’m not seeing very good success. If you know of any please share.
    Thank you!

  7. wandfolie表示:

    At this moment I am going away to do my breakfast, later
    than having my breakfast coming yet again to read more news.

  8. Hello, i believe that i noticed you visited my weblog thus i
    came to return the desire?.I am trying to in finding things
    to improve my website!I assume its ok to make use of
    a few of your ideas!!

  9. DarrenUnjuh表示:

    http://lisinopril1st.com/# lisinopril hct

  10. DarrenUnjuh表示:

    https://iverfast.com/# where to buy ivermectin

  11. danielgacisp表示:

    Я присоединяюсь ко всему выше сказанному. Можем пообщаться на эту тему.
    тут работают знающие мастера, и инженеры по аварийке компьютеров, оргтехники, имеющие профессиональную подготовку, профильные знания, компьютерная помощь в Иваново опыт комфортной работы и широкую специализацию.

  12. Sazrwvv表示:

    Стоимость дипломов высшего и среднего образования и как избежать подделок

    ultras.lv/viewtopic.php?f=12&t=2064

  13. Your means of explaining all in this post is actually good, every one be able to
    easily be aware of it, Thanks a lot https://fenestrationdessommets.com/

  14. BrandenSlomy表示:

    amoxicillin order online no prescription: amoxil – amoxicillin 500 tablet

  15. DerekWab表示:

    кухни на заказ спб недорого – идеальное решение для качественной кухни по доступной цене.

  16. Every weekend i used to go to see this site, for the
    reason that i want enjoyment, since this this web page conations truly nice funny information too.

  17. Hi there colleagues, how is all, and what you
    desire to say on the topic of this post, in my view its actually
    remarkable in support of me.

  18. Hey there are using WordPress for your site platform?

    I’m new to the blog world but I’m trying to get started and create my own. Do you need any html coding knowledge
    to make your own blog? Any help would be really appreciated!

  19. Thanks for finally writing about > JS 依照元素出現數量排序 –
    馬老師 雲端研究室 < Liked it!

  20. Today, I went to the beach with my children. I found a sea shell and gave it to
    my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She placed the shell to
    her ear and screamed. There was a hermit crab inside and it
    pinched her ear. She never wants to go back!
    LoL I know this is entirely off topic but I had
    to tell someone!

發佈留言

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