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,364,598 Responses

  1. Markdob表示:

    Всем привет! Может кто знает, где почитатьразные статьи о недвижимости? Сейчас читаю – https://integral-sb.ru

  2. Markdob表示:

    Всем привет! Подскажите, где почитатьразные блоги о недвижимости? Сейчас читаю – https://integral-sb.ru

  3. I know this site offers quality dependent articles and additional
    stuff, is there any other site which provides such
    stuff in quality?

  4. JacobLoody表示:

    кухни на заказ от производителя — Эксклюзивные кухни на заказ от производителя с гарантией качества.

  5. smoky shop предлагает вам уникальную возможность ознакомиться с нашими pod системы https://milky-vape.hashnode.dev/lost-vape-epoch-kompaktnyj-i-moshnyj-vejp-dlya-ukrainy топ!

  6. walet69 login表示:

    Pretty section of content. I just stumbled upon your blog and
    in accession capital to assert that I acquire actually enjoyed account your
    blog posts. Any way I’ll be subscribing to your augment and even I achievement
    you access consistently quickly.

    Look at my blog :: walet69 login

  7. video chat表示:

    I’m very pleased to discover this website.

    I need to to thank you for your time for this particularly wonderful read!!

    I definitely liked every part of it and i also have you
    saved to fav to look at new things on your web site.

    Also visit my web page; video chat

  8. Markdob表示:

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

  9. Liner AI表示:

    This is very attention-grabbing, You’re an excessively skilled blogger.
    I have joined your rss feed and look ahead to in quest of more of your fantastic post.
    Additionally, I’ve shared your site in my social networks

    Feel free to surf to my blog: Liner AI

  10. Markdob表示:

    Приветствую. Может кто знает, где найтиразные статьи о недвижимости? Пока нашел – https://integral-sb.ru

  11. Medicines prescribing information. Effects of Drug Abuse.
    what does losartan do
    Everything trends of medicine. Get now.

  12. Mattie Bell表示:

    Phone repair costs can really add up! I’ve been researching ways to save money on repairs, and samsung repair has some excellent suggestions worth checking out

  13. aiporn.pw表示:

    Thanks for sharing your thoughts on site. Regards

  14. Caroline Pope表示:

    Happy to see discussions about ethical considerations in digital marketing for lawyers—it’s crucial! Explore further discussions through seo for lagal firm

  15. Markdob表示:

    Приветствую. Подскажите, где найтиразные блоги о недвижимости? Сейчас читаю – https://integral-sb.ru

  16. It’s a pity you don’t have a donate button! I’d certainly donate to this outstanding blog!

    I suppose for now i’ll settle for book-marking
    and adding your RSS feed to my Google account. I look forward to fresh updates and will share
    this blog with my Facebook group. Talk soon!

  17. Justin James表示:

    Thoughtful examination of how user intent affects keyword selection was enlightening—find practical examples through local seo company

  18. Josie Sutton表示:

    Loved your perspective on using email marketing alongside SEO efforts—it’s all about nurturing leads effectively! For more tips seo company for law firm

  19. Markdob表示:

    Всем привет! Подскажите, где почитатьполезные блоги о недвижимости? Сейчас читаю – https://integral-sb.ru

  20. Roger Hansen表示:

    I thoroughly enjoyed your discussion around crafting compelling meta descriptions—they’re truly impactful yet often ignored; see further techniques over at local seo law firm

  21. Amelia Moore表示:

    How do you guys feel about using recycled materials in new construction like reclaimed wood paired with modern metals? Visit my site for unique combinations: roofing company

  22. BrandenSlomy表示:

    buy dapoxetine online: priligy – buy priligy max pharm

  23. Lily Osborne表示:

    Your insights are incredibly helpful—working with an effective # seo marketing for lawyers # could transform our client

  24. Hati-hati kalau nemu link yang tampilannya mirip sama
    situs terkenal. Bisa aja itu cuma trik phishing. Jangan kasih info pribadi tanpa cek URL
    dulu!.

  25. Lulu Floyd表示:

    What a great reminder about maintaining an active blog as a lawyer! Fresh content boosts SEO significantly digital marketing for law firms

發佈留言

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