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,413 Responses

  1. Medication information leaflet. What side effects can this medication cause?
    effects of mirtazapine on sleep disturbance under
    Some information about medicines. Read here.

  2. Eden表示:

    10 Easy Ways To Figure The Mazda Key Fob You’re Looking For mazda car
    keys replacements [Eden]

  3. This is a very good tip especially to those new to the blogosphere.

    Short but very accurate information… Thanks for sharing this one.
    A must read article!

  4. Retinols表示:

    Undeniably consider that that you said. Your favourite reason seemed to be
    at the net the simplest factor to take into account
    of. I say to you, I definitely get irked whilst people think
    about worries that they just don’t realize about. You managed to
    hit the nail upon the top and also outlined out the entire thing without having side effect ,
    people can take a signal. Will probably be back to get more.
    Thank you

  5. Nikefut表示:

    drug markets dark web darknet market https://darknetmarketstore.com/ – dark market list

  6. slot bet 10表示:

    Somebody essentially lend a hand to make severely articles
    I’d state. This is the very first time I frequented
    your website page and to this point? I surprised with the
    research you made to make this particular post amazing.
    Wonderful activity!

  7. EdgarFed表示:

    Discovered a gem of an article you’ll enjoy this one http://mosdmit.flybb.ru/viewtopic.php?f=2&t=484&sid=78c3b4a4fa04fb943cbb921af7aa7af7

  8. Aptorkbit App表示:

    Asking questions are truly pleasant thing if you are not understanding anything entirely,
    but this paragraph offers fastidious understanding even.

  9. Thanks for the auspicious writeup. It in reality used to be a
    amusement account it. Glance complicated to more introduced agreeable from
    you! However, how can we keep in touch?

  10. We stumbled over here by a different page and thought I should check things out.
    I like what I see so now i’m following you. Look forward
    to looking at your web page repeatedly.

  11. При этом вы получаете доступ к
    лицензионным игровым автоматам, что в долгосрочной перспективе будет гораздо выгоднее и
    приятнее для вашего игрового опыта.

  12. First of all I would like to say superb blog! I had a quick question that
    I’d like to ask if you don’t mind. I was interested to find out how you center yourself and clear your thoughts before writing.

    I have had a hard time clearing my thoughts in getting my
    thoughts out. I truly do take pleasure in writing
    but it just seems like the first 10 to 15 minutes are generally lost simply just trying to figure out how to begin. Any suggestions or hints?
    Thank you!

  13. Среди множества азартных проектов, которые ориентированы на русскоязычную аудиторию, заметно выделяется онлайн-казино Friends.

  14. Appreciate the recommendation. Let me try it out.

  15. LeonardKnism表示:

    https://tir92.ru/ – Мы знаем, как сделать вашу кухню комфортной и стильной.

  16. I just could not leave your site prior to suggesting
    that I actually enjoyed the usual information a person supply in your visitors?

    Is going to be back ceaselessly in order to investigate
    cross-check new posts

  17. See What Affordable SEO Firm Near Me Tricks The Celebs Are Using affordable seo firm near me

  18. Hello all, here every one is sharing these experience, so it’s good to read this weblog,
    and I used to visit this website daily.

  19. My brother recommended I might like this web site.
    He was once entirely right. This submit actually made my day.
    You can not believe simply how so much time I had spent for this information! Thanks!

  20. Nikefut表示:

    blackweb how to get on dark web https://darknetmarketstore.com/ – darkmarket list

  21. forkpart.ru表示:

    Ваш погрузчик заслуживает только лучшего! На forkpart.ru представлен надежный шинокомплект , который выдерживает любые нагрузки. Прочные материалы, точная посадка и долговечность делают этот комплект идеальным выбором. Мы гарантируем доступные цены и быструю доставку. Сделайте свой заказ уже сегодня и убедитесь в качестве продукции forkpart.ru.

  22. Hi there, i read your blog occasionally and i own a
    similar one and i was just wondering if you get
    a lot of spam remarks? If so how do you stop it, any plugin or anything you can suggest?
    I get so much lately it’s driving me crazy so any help is very much appreciated.

  23. Узнай все о операция по удалению полипа эндометрия в маткеудаление полипа эндометрия цена

  24. Markdob表示:

    Всем привет! Подскажите, где почитатьразные статьи о недвижимости? Пока нашел – https://keramomix23.ru

發佈留言

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