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,368,018 Responses

  1. Cars表示:

    Ten Replacement Ferrari Key Uk That Will Actually Change Your Life Cars

  2. Jeremypag表示:

    buy rybelsus online semaglutide cost buy semaglutide online

  3. Jamesses表示:

    Познакомьтесь капля нашим проф коллективом, яже создаёт чудесную этажерка, воплощая ваши мечты в течение реальность https://cehitae2kuhnishki.ru/.

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

  5. BarryDof表示:

    https://ozempic.art/# buy cheap ozempic

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

  7. If some one needs expert view regarding blogging then i recommend him/her to pay
    a visit this blog, Keep up the nice work.

    Also visit my blog Top KL caterer

  8. You actually make it seem so easy with your presentation but I find this topic
    to be really something which I think I would
    never understand. It seems too complex and extremely broad for me.
    I’m looking forward for your next post, I’ll try to get
    the hang of it!

  9. Slot Olympus表示:

    For hottest news you have to visit internet and on the web
    I found this website as a best site for most up-to-date updates.

  10. xxx表示:

    Hurrah! After all I got a website from where I know how
    to genuinely take useful data regarding my study and knowledge.

  11. Сервисный центр предлагает ремонт кондиционера ecostar недорого ремонт кондиционера ecostar на дому

  12. Frankevild表示:

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

  13. Armandoknot表示:

    Как улучшить настроение другу? Посмотрите
    смешные анекдоты и поделитесь с близкими.

  14. Frankevild表示:

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

  15. RamonRek表示:

    rybelsus coupon: cheapest rybelsus pills – cheapest rybelsus pills

  16. Сервисный центр предлагает ремонт кофемашин centek недорого отремонтировать кофемашины centek

  17. A Mortgage Loan Modification Can Stop A Judicial Foreclosure Case
    신용불량자 대출

  18. Frankevild表示:

    https://ozempic.art/# ozempic coupon

  19. Bunk Beds With Single And Double Tools To Help You Manage
    Your Everyday Lifethe Only Bunk Beds With Single And
    Double Trick Every Individual Should Be Able To
    bunk beds With single and double

  20. 14 Questions You Shouldn’t Be Afraid To Ask About Upvc Door Repairs Near
    Me emergency Upvc door repairs near Me (clashofcryptos.trade)

  21. Hey! Do you know if they make any plugins to assist
    with Search Engine Optimization? I’m trying to get my
    blog to rank for some targeted keywords but I’m not seeing very
    good results. If you know of any please share. Appreciate it!

  22. Pinterest表示:

    After I initially left a comment I seem to have clicked on the -Notify me when new comments are added- checkbox and from now on whenever a comment is added I receive four emails with the same comment.
    Perhaps there is a way you can remove me from that service?
    Thanks!

    Feel free to surf to my web page – Pinterest

  23. Jeremypag表示:

    ozempic cost ozempic generic buy ozempic

  24. HaroldBig表示:

    buy cheap ozempic: Ozempic without insurance – ozempic coupon

  25. the rapture表示:

    Neat blog! Is your theme custom made or did
    you download it from somewhere? A theme like yours with a few simple
    tweeks would really make my blog jump out. Please let me know where you got your design. Thanks

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

  27. HaroldBig表示:

    rybelsus pill: cheapest rybelsus pills – cheapest rybelsus pills

發佈留言

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