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,483,164 Responses

  1. the perpetrator can create situations in which they are alone with the child,ラブドールsuch as taking them on overnight stays or outings without the suspicion of the parents and,

  2. There are various tools and websites that allegation to allow
    users to view private Instagram profiles, but it’s important to open these bearing in mind
    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 guide to scams. The safest and most ethical showing off to view private instagram without human verification a private
    profile is to send a follow request directly to the user.
    Always prioritize privacy and veneration in your online interactions.

  3. AlbertDuM表示:

    antiplatelet drug: Clopidogrel Best Prices – plavix medication

  4. Nikefut表示:

    blackweb official website bitcoin dark web darknet market links

  5. AlbertDuM表示:

    Plavix generic price: plavix medication – Plavix generic price

  6. Thank you for another magnificent article.
    Where else could anyone get that kind of info in such a perfect approach
    of writing? I have a presentation next week, and I am at the look for such information.

  7. Kennethacite表示:

    Patient drug resource. Medication effects explained.
    buy valtrex
    Medication effects explained. Get info immediately.

  8. Isabell Sarra表示:

    Residential Development become further away from City or Establish Town

  9. click link表示:

    Now I am going away to do my breakfast, later than having my breakfast coming yet again to read other news.

  10. AlbertDuM表示:

    zestril medication: buy Lisinopril 1st – buy Lisinopril 1st

  11. BrandenSlomy表示:

    priligy: dapoxetine online – dapoxetine price

  12. child abuse表示:

    Woah! I’m really loving the template/theme of this website.

    It’s simple, yet effective. A lot of times
    it’s difficult to get that “perfect balance” between usability and visual appeal.
    I must say you have done a great job with this.
    Also, the blog loads very quick for me on Internet explorer.
    Outstanding Blog!

  13. You need to be a part of a contest for one of the
    most useful blogs on the internet. I will highly recommend
    this web site!

  14. Предлагаем услуги профессиональных инженеров офицальной мастерской.
    Еслли вы искали сервисный центр lg в москве, можете посмотреть на сайте: сервисный центр lg в москве
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  15. If your only experience of sex dolls is pop culture images of the old blow-up dolls of the 60s and 70s, 人形 エロit’s time to upgrade your knowledge of sex dolls!

  16. Land price always will increase because of demands

  17. My partner and I stumbled over here from a different web page and thought I might
    as well check things out. I like what I see so now i am following you.
    Look forward to exploring your web page for a second time.

  18. tummy tuck表示:

    constantly i used to read smaller articles or reviews
    that also clear their motive, and that is also happening with this article which I am reading at this time.

    Also visit my website tummy tuck

  19. Mariosep表示:

    Пошаговое руководство по восстановлению прозрачности фар с помощью наждачной бумаги разной зернистости. Советы по выбору материалов и технике обработки наждачка

  20. Sweet blog! I found it while browsing on Yahoo News. Do you
    have any tips on how to get listed in Yahoo News?
    I’ve been trying for a while but I never seem to
    get there! Appreciate it

  21. Hello there, You have done an incredible job.
    I will definitely digg it and personally recommend
    to my friends. I am sure they’ll be benefited from this web site.

發佈留言

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