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,244,178 Responses

  1. BrandenSlomy表示:

    where can i order prednisone 20mg: cheap prednisone – prednisone over the counter uk

  2. Узнай все о варикоцеле левого яичка варикоцеле причины возникновения

  3. word ai表示:

    What Is The Reason? Ai Rewrite Content Is Fast Increasing To Be The Hot Trend For
    2022 word ai

  4. I am really loving the theme/design of your website.
    Do you ever run into any browser compatibility issues?
    A number of my blog readers have complained about my website not
    operating correctly in Explorer but looks great in Safari. Do you have any recommendations to
    help fix this issue?

  5. Uazrucu表示:

    Как получить диплом о среднем образовании в Москве и других городах

    unitedindoorfootball.com/kupit-attestat-11-klassov-tsena-v-ryazani.html

  6. Medicines information leaflet. Generic Name.
    how to come off spironolactone
    Some information about meds. Read here.

  7. Antonia表示:

    The Main Problem With Pragmatic, And What You Can Do To
    Fix It 프라그마틱 게임 (Antonia)

  8. The 10 Most Terrifying Things About Casino Online Crypto casino online crypto

  9. Узнай все о признаки варикоцеле варикоцеле у мужчин

  10. I really like what you guys are usually up too.

    This kind of clever work and exposure! Keep up the wonderful works guys I’ve
    incorporated you guys to my blogroll.

  11. Тут можно преобрести купить оружейный сейф в интернет магазин сейф оружейный

  12. Dereketerm表示:

    prednisone 4mg: raypharm – prednisone uk over the counter

  13. Узнай все о варикоцеле и потенция на что влияет варикоцеле

  14. StevenNub表示:

    amoxicillin pharmacy price: Amoxicillin for sale – where to buy amoxicillin 500mg without prescription

  15. An In-Depth Look Into The Future: What Will The 2 In 1 Prams
    Industry Look Like In 10 Years? car seat 2 in 1 stroller (https://xia.h5gamebbs.cndw.com)

  16. Thank you for any other informative web site. Where else may I am getting
    that kind of information written in such a perfect way?
    I’ve a undertaking that I’m just now running on, and I’ve
    been on the look out for such information.

  17. I do not even know the way I stopped up here, but I
    thought this publish used to be great. I don’t know who you might
    be however definitely you are going to a famous blogger in case you aren’t already.
    Cheers!

  18. Dereketerm表示:

    medicine prednisone 10mg: ray pharm – medicine prednisone 10mg

  19. blog here表示:

    Hmm it looks like your site ate my first comment (it was super long) so I guess I’ll just sum it up what
    I had written and say, I’m thoroughly enjoying your blog.
    I as well am an aspiring blog blogger but I’m still new to everything.
    Do you have any recommendations for rookie blog writers?
    I’d certainly appreciate it.

  20. BrettVup表示:

    Link Building Services
    [url=#filelinks[“C:\xrum\link_building_services_1_2810_2811_1\URL.txt”,1,N]]best link building services[/url]
    Hey there, future SEO rockstar! Ready to skyrocket your business to new heights? Let’s dive into the exciting world of link building services that can seriously amp up your online presence. Whether you’re just starting out or looking to boost your existing strategy, we’ve got the lowdown on the coolest methods out there—think crowd marketing, guest posting, PBNs, and more!
    Why Link Building is Your New Best Friend
    First things first: why should you care about link building? Well, in the digital universe, backlinks are like high-fives from other websites telling search engines, “Hey, this site is pretty cool!” The more quality high-fives you get, the more popular you become in the eyes of Google and friends. And you know what that means—higher rankings, more traffic, and a whole lot of new customers knocking on your virtual door.
    Guest Posting: Share Your Voice with the World
    Imagine getting to share your ideas on someone else’s platform and gaining their audience’s trust. That’s guest posting in a nutshell! You create killer content for other websites in your niche, and in return, you get a sweet backlink to your site. Why It’s Cool: You tap into new audiences, build your brand’s credibility, and boost your SEO. Pro Tip: Make sure your content is top-notch and adds real value. No one likes fluff!
    Crowd Marketing: Join the Conversation
    Crowd marketing is all about jumping into online communities—forums, social media groups, you name it—and sharing your wisdom. It’s not about shameless plugs; it’s about being genuinely helpful. Why It’s Cool: You build relationships, establish yourself as an expert, and earn organic backlinks. Pro Tip: Be authentic. People can spot a fake from a mile away.

  21. Nikefut表示:

    darkmarket 2024 dark market link dark web sites links

發佈留言

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