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,467,175 Responses

  1. JasonUnsoG表示:

    https://denemebonusuverensiteler25.com/# yeni deneme bonusu veren siteler

  2. Thanks for the thorough analysis. More info at roof repair in littleton

  3. Hulda Mack表示:

    Thanks for the insightful write-up. More like this at بلفاروپلاستی چیست

  4. BradleyEdino表示:

    slot siteleri guvenilir slot siteleri slot casino siteleri

  5. Stellar service from our selected ###anything### made all the difference during this journey!!! San Diego vehicle shipping

  6. JacobLoody表示:

    http://arch-mag.ru/ — Простое и удобное решение для заказа вашей новой кухни.

  7. Lina Diaz表示:

    I like the distinct dining experience at Brazilian steakhouses! The gaucho-style service adds so much to the dish brazilian steakhouse restaurant near me

  8. 5 Lawyer Train Projects For Any Budget lawyer truck accident

  9. BradleyEdino表示:

    Deneme Bonusu Veren Siteler deneme bonusu veren bГјtГјn siteler canl? casino siteleri

  10. This was a wonderful post. Check out pavers company for more

  11. Ernest Young表示:

    I have actually been trying to find a great animal groomer in my area at home grooming near me

  12. web page表示:

    Ищете способ быстро решить финансовые вопросы?
    Наши кредиты — это именно то, что вам нужно!

    Никаких скрытых платежей, простая подача заявки и
    решение за 15 минут.
    Рассматриваем сумму от 10,000 до 1,000,000 рублей.
    Гибкие условия погашения и
    низкие процентные ставки делают наши предложения выгодными.

    Не ждите, действуйте сейчас! Звоните и узнайте больше о своих
    возможностях!===>>
    Деньги на дом в Ачинске

  13. Nancy Brooks表示:

    Fantastic post! Discover more at pool cleaning near me

  14. Generative AI表示:

    I blog quite often and I really appreciate your information. The article has
    really peaked my interest. I’m going to take a note of your website and keep checking
    for new information about once per week. I subscribed to your Feed as well.

  15. Garrett Blake表示:

    Helpful suggestions! For more, visit roof repair near me

  16. 양산 1등 돈 많이 버는 곳은 바로 양산 노래방알바입니다

  17. JamesIncew表示:

    Круглозвенные цепи — это не просто элемент механики, а настоящая находка для бизнеса! Они широко используются в различных отраслях: от сельского хозяйства до строительства, обеспечивая надежную передачу усилия и долговечность – найти подшипник по размерам.

  18. Buying a home in Tacoma requires careful planning, especially with mortgages Tacoma Home Loan

  19. Hey! Do you use Twitter? I’d like to follow you if that would be okay.
    I’m absolutely enjoying your blog and look forward
    to new posts.

  20. BradleyEdino表示:

    deneme bonusu veren siteler deneme bonusu veren yeni siteler deneme bonusu veren siteler yeni

  21. kinhdanantoan表示:

    I am extremely impressed along with your writing skills and also
    with the layout for your weblog. Is that this a paid
    topic or did you modify it your self? Either
    way stay up the excellent high quality writing, it’s rare to look a nice blog like this one nowadays..

  22. Emil表示:

    Outstanding story there. What occurred after? Good luck!

  23. FrankEmine表示:

    slot siteleri: en cok kazand?ran slot oyunlar? – az parayla cok kazandiran slot oyunlar?

  24. truck lawyers表示:

    You’ll Never Be Able To Figure Out This Truck Lawyers Near Me’s Tricks truck lawyers

  25. JasonUnsoG表示:

    https://sweetbonanza25.com/# sweet bonanza giris

  26. JasonUnsoG表示:

    http://casinositeleri25.com/# canl? casino siteleri

發佈留言

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