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,366,268 Responses

  1. Hi there colleagues, how is all, and what you desire to say on the topic of this
    article, in my view its truly remarkable designed
    for me.

  2. DanielAbice表示:

    http://amoxstar.com/# canadian pharmacy amoxicillin

  3. koi toto表示:

    I don’t even know how I ended up here, but I thought this post
    was great. I don’t know who you are but definitely you’re going to a famous blogger if you
    are not already 😉 Cheers!

  4. KennethPah表示:

    buy amoxicillin online with paypal amoxicillin 500 mg for sale amoxicillin online canada

  5. 골드페이表示:

    Online Roulette Games 골드페이

  6. Nikefut表示:

    drug markets onion dark web market links dark web market list

  7. Здесь можно домашний сейф купить купить сейф для дома в москве

  8. Здесь можно сейф для дома купить домашний сейф

  9. SamuelBix表示:

    can i get clomid no prescription: can you get cheap clomid online – order cheap clomid without prescription

  10. Hi colleagues, fastidious paragraph and nice arguments commented here,
    I am genuinely enjoying by these.

  11. I do believe all of the ideas you’ve presented to your post.
    They’re really convincing and will certainly work. Nonetheless,
    the posts are very quick for starters. Could you
    please prolong them a little from subsequent time? Thanks for the
    post.

  12. porno表示:

    Have you ever considered creating an ebook or guest authoring
    on other sites? I have a blog based on the same information you discuss and would love to have you share
    some stories/information. I know my readers would value your
    work. If you are even remotely interested, feel free to send me an email.

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

  14. where can i buy in canada doxycycline hyclate 100mg tablets where can i buy cheap doxycycline without prescription can you buy doxycycline over the counter in america
    can i order cheap doxycycline no prescription where can i buy cheap doxycycline price how to buy generic doxycycline for sale
    generic doxycycline without prescription
    doxycycline 100mg dosage for adults buying generic doxycycline without prescription where can i buy cheap doxycycline tablets
    where can i buy cheap doxycycline pill doxycycline 100 mg uses how can i get cheap doxycycline tablets

  15. This was highly educational. For more, visit restoration specialists near me

  16. Здесь можно домашний сейф купить купить сейфы для дома

  17. Herman Larson表示:

    I loved your discussion on social media algorithms, so insightful! More details can be found at digital marketing

  18. Nikefut表示:

    dark web access drug markets dark web black internet

  19. The future of digital marketing looks bright with AI advancements! Read more about it at content marketing

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

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

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

  23. hello!,I like your writing so so much! proportion we keep up
    a correspondence extra about your article on AOL?
    I require a specialist in this area to resolve my problem.
    Maybe that is you! Taking a look ahead to see you.

  24. SamuelBix表示:

    clomid without prescription: where to buy clomid without prescription – get clomid now

發佈留言

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