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,369,026 Responses

  1. BarryDof表示:

    http://rybelsus.shop/# buy semaglutide online

  2. Сервисный центр предлагает ремонт телефона vivo адреса качественный ремонт телефонов vivo

  3. I’ve been exploring for a little bit for any high quality
    articles or weblog posts in this kind of space .
    Exploring in Yahoo I at last stumbled upon this site.
    Reading this info So i’m happy to show that I have an incredibly excellent uncanny
    feeling I came upon exactly what I needed. I so much surely will make certain to do not forget this website and give it a glance on a constant basis.

  4. I have read so many posts about the blogger lovers
    but this piece of writing is truly a good post, keep
    it up.

    Here is my webpage mega555kf7lsmb54yd6etzginolhxxi4ytdoma2rf77ngq55fhfcnyid.onion

  5. pafipakam.org表示:

    Hi there! Do you use Twitter? I’d like to follow you if that would be ok.

    I’m undoubtedly enjoying your blog and look forward to
    new posts.

  6. HaroldBig表示:

    buy ozempic pills online: buy ozempic pills online – ozempic online

  7. 문화 예술 축제 관광 콘텐츠가 넘쳐나는 문화도시 부천의 부천 룸싸롱에서 새로운 감동을 한 번 받아 보세요

  8. titwank表示:

    Useful info. Lucky me I found your site unintentionally, and I am
    shocked why this coincidence did not came about in advance!

    I bookmarked it.

  9. What’s Going down i am new to this, I stumbled upon this I have discovered It
    positively useful and it has helped me out loads.
    I hope to give a contribution & help different users like its aided
    me. Great job.

  10. Hey! I just wanted to ask if you ever have any
    trouble with hackers? My last blog (wordpress) was hacked and I ended up losing many months of hard work due to no back up.
    Do you have any solutions to prevent hackers?

  11. Jeremypag表示:

    rybelsus price semaglutide online semaglutide tablets

  12. Get More Info表示:

    Very great post. I just stumbled upon your weblog and wanted to mention that I’ve really enjoyed surfing around your weblog posts.
    After all I will be subscribing for your feed and I’m hoping you write once
    more soon!

  13. Jeremypag表示:

    rybelsus price semaglutide online buy semaglutide online

  14. Darrellrit表示:

    Medication guide available. Find medicine information.
    clarithromycin online uk
    Drug guide provided. Read about pills.

  15. 7 Simple Tips For Making A Statement With Your Latest Sport Toto Result 메이저사이트

  16. I visited many sites however the audio feature for audio songs existing at
    this website is really marvelous.

    My webpage :: Best Counseling in Pensacola Florida

  17. Hello there, just became aware of your blog through Google, and found that it’s truly informative.
    I am going to watch out for brussels. I will be grateful
    if you continue this in future. Numerous people
    will be benefited from your writing. Cheers!

  18. HaroldBig表示:

    Ozempic without insurance: ozempic online – buy ozempic pills online

  19. Jeremypag表示:

    ozempic ozempic online ozempic coupon

  20. Angeles表示:

    Fire Pits & Chimineas Tips To Relax Your Everyday Lifethe Only Fire Pits
    & Chimineas Trick Every Person Should Know fire pits & chimineas (Angeles)

  21. HaroldBig表示:

    ozempic cost: buy ozempic – ozempic cost

  22. HaroldBig表示:

    buy semaglutide online: cheapest rybelsus pills – semaglutide online

  23. تراتل xu7 دو دهنه (پژو 405 ، سمند
    ، پارس)
    Throttle 2 holes xu7 (Peugeot 405)
    تراتل دو دهنه xu7 را میتوانیم قویترین منیفولد موجود برای انجین xu7 بدانیم که بیشترین توان را ارائه کرده است.

    این منیفولد توانایی کارکرد در تمامی شرایط آب و هوایی را دارد
    و میتواند تا 70% توان خودرو را بهبود
    بخشد. در زیر اطلاعات کاملتری در این زمینه ارائه شده
    است که میتوانید مطالعه فرمایید.

  24. Desiree表示:

    Hey there, I think your blog might be having browser compatibility issues.
    When I look at your blog in Opera, it looks fine but when opening in Internet
    Explorer, it has some overlapping. I just wanted to
    give you a quick heads up! Other then that, excellent
    blog!

  25. RamonRek表示:

    rybelsus coupon: buy rybelsus online – rybelsus coupon

  26. Very great post. I just stumbled upon your weblog and wished to mention that I have
    really enjoyed browsing your weblog posts. After all I
    will be subscribing to your rss feed and I’m hoping you write again very soon!

  27. Профессиональный сервисный центр по ремонту автомагнитол в Москве.
    Мы предлагаем: ремонт автомагнитол в москве
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  28. Jeremypag表示:

    Ozempic without insurance ozempic cost buy cheap ozempic

發佈留言

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