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,235,989 Responses

  1. I really like your blog.. very nice colors & theme.

    Did you create this website yourself or did you hire someone to do it for you?
    Plz reply as I’m looking to create my own blog and would like to find out where u got this from.

    thanks

    my site; herpesyl review

  2. Online Gambling – Its Advantages And Disadvantages 헝그리
    샤크 에볼루션 버그판 (http://www.metooo.co.uk)

  3. Great weblog right here! Additionally your web site so much
    up fast! What web host are you using? Can I am getting your affiliate link for your host?

    I wish my web site loaded up as quickly as yours lol

    my webpage dentavim bbb reviews

  4. Exceptional post however I was wondering if you
    could write a litte more on this subject? I’d be very grateful
    if you could elaborate a little bit more. Bless you!

  5. KevinSounc表示:

    https://denemebonusuverensiteler.win/# bonus veren siteler

  6. Darrelherse表示:

    slot casino siteleri: guvenilir slot siteleri – deneme bonusu veren slot siteleri

  7. See What Window Repair Bromley Tricks The Celebs Are Using
    window repair bromley

  8. Yukiko表示:

    What i do not realize is in truth how you’re now not really a lot
    more smartly-preferred than you may be right now.
    You’re very intelligent. You understand thus significantly on the subject of this topic, produced
    me personally believe it from so many various angles. Its like men and women are
    not fascinated except it’s one thing to accomplish with Lady gaga!
    Your personal stuffs nice. All the time take care of it up!

  9. KevinSounc表示:

    http://denemebonusuverensiteler.win/# deneme bonusu veren siteler

  10. Thank you for another wonderful article. Where else
    could anybody get that type of info in such a perfect method
    of writing? I have a presentation subsequent week,
    and I am on the search for such info.

  11. Maybell表示:

    I just like the valuable info you provide on your articles.
    I’ll bookmark your blog and test once more right here regularly.
    I’m reasonably certain I’ll be informed plenty of new stuff proper here!
    Best of luck for the following!

  12. Darrelherse表示:

    yasal slot siteleri: bonus veren casino slot siteleri – deneme bonusu veren slot siteleri

  13. You really make it seem so easy with your presentation but I find this matter to be really something that I think
    I would never understand. It seems too complicated and very broad for me.

    I am looking forward for your next post, I will try to get the hang of it!

  14. Hi there, I enjoy reading through your article post.
    I like to write a little comment to support you.

  15. Very descriptive article, I enjoyed that bit. Will there be a part 2?

  16. “Ask Me Anything,” 10 Responses To Your Questions About Mesothelioma Legal Question mesothelioma Litigation

  17. each time i used to read smaller posts that as well clear their motive, and that
    is also happening with this piece of writing which I am reading at this place.

  18. KevinSounc表示:

    https://slotsiteleri.bid/# slot siteleri bonus veren

  19. gay_vrpr表示:

    Ставки на спорт для ЛГБТ сообщества | Спортивные ставки для LGBTQ+ на 1xbet | Полезная информация о 1xbet для геев | Как делать ставки на 1xbet, если вы гей | Gay ставки на 1xbet: всё, что вам нужно знать
    porbhub gay in 1xbet https://1xbetcasinogayclub-ar.com/ .

  20. I know this website gives quality depending content and additional data, is there any other
    website which provides these data in quality?

  21. Доставка из Китая с таможенными услугами – это профессиональное решение
    для импорта товаров из Китая, включающее в себя
    организацию перевозки, таможенное оформление и
    сопутствующие услуги. Мы предоставляем полный спектр услуг,
    связанных доставка груза китай включая организацию международных перевозок, таможенное оформление,
    сертификацию и страхование грузов.
    Наши специалисты помогут вам выбрать оптимальный маршрут и вид транспорта, оформить необходимые документы
    и декларации, а также проконсультируют
    по вопросам налогообложения и таможенного законодательства.

  22. The Little-Known Benefits Of Harrow Door And Window repairs to double glazed windows

  23. Fantastic website. Lots of useful information here. I’m sending it to a few friends ans additionally
    sharing in delicious. And certainly, thanks in your sweat!

  24. It’s awesome to go to see this web page and reading the views of all colleagues regarding this post, while I am also zealous of getting know-how.

  25. thimbles game表示:

    Hmm it seems like your website ate my first comment (it was
    super long) so I guess I’ll just sum it up what I submitted and say, I’m thoroughly
    enjoying your blog. I too am an aspiring blog blogger
    but I’m still new to the whole thing. Do you have any recommendations for
    beginner blog writers? I’d definitely appreciate it.

  26. Hi, I do believe this is a great blog. I stumbledupon it 😉 I’m going to
    return yet again since I book marked it. Money and freedom is the best way to change, may you
    be rich and continue to guide others.

  27. Kennethmab表示:

    Официальный телеграм Sukaaa предлагает новым игрокам бонус 325% в 4 этапа, за активное повышение уровня – игрок получает круглосуточную поддержку и участие в турнирах. Новых клиентов привлекает не только бонус бездеп за регистрацию, но и дизайн telegram SYKAAA official на сайте наглядное меню, которое позволяет в пару кликов найти нужный провайдер, выбрать игру или сделать депозит.

  28. KevinSounc表示:

    https://denemebonusuverensiteler.win/# deneme bonusu veren siteler

發佈留言

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