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,194,873 Responses

  1. Medication information sheet. What side effects can this medication cause?
    how to buy cheap zofran without prescription
    Actual news about drugs. Read information now.

  2. Xpert Foundation Repair
    Ríօ Grande Valley, TX 78582, United Տtates
    9562653062
    z leveling enforced

  3. gay porn表示:

    online slot

  4. BomesJoype表示:

    Lorem Ipsum has been the industry’s standard dummy text https://ajf-boischauffage.fr/fnuyj of type and scrambled it to make a type specimen book.

  5. Reclaiming your money shouldn’t be a hassle. That’s why our process
    is user-friendly and open.
    You just need to supply some basic information, and we’ll handle the rest.

    Don’t allow technical problems prevent you from your savings.
    We’re committed to ensure the return of every penny.

  6. Heya i’m for the first time here. I found this board and I
    in finding It truly useful & it helped me out much. I am hoping to offer
    one thing again and help others like you aided
    me.

  7. t-shirt表示:

    Starting a t-shirt shop is an rewarding opportunity for entrepreneurs looking to explore the clothing
    industry. With a solid plan and commitment, your t-shirt shop could prosper and become a profitable business.
    Here are some key steps to keep in mind when opening a t-shirt
    shop.

    ### Initial Planning

    Developing a thorough strategy is essential for the success and growth of your t-shirt shop.
    This blueprint should include your target market, promotional methods, budget, and objectives.

    Identifying your customer base will help tailor your products and promotional activities to cater to their interests.

    ### Design and Production

    Creating the design of your t-shirts is a key factor in drawing buyers.
    Consider hiring talented designers to develop unique and stylish patterns that appeal to your
    target market. Think about using various printing methods, like screen printing, direct-to-garment printing,
    and heat transfer, according to your resources and the quality level of the t-shirts.

    ### Choosing Suppliers

    Selecting dependable vendors for your t-shirts is essential
    to guarantee reliable quality. Search for vendors that offer premium blank t-shirts in various sizes.
    Creating a strong partnership with your vendors can help maintain timely
    shipments and reasonable pricing.

    ### Building an Online Presence

    In today’s online age, having an e-commerce site is important for reaching a broader audience.
    Create an user-friendly and functional online store to showcase your t-shirts.
    Utilize clear images and informative product details
    to offer visitors a clear idea of what they are purchasing.
    Look into including options like safe transactions methods, ratings, and social sharing links to improve
    customer interaction.

    ### Advertising and Marketing

    Effective marketing is essential to attracting customers to your t-shirt shop.
    Leverage multiple advertising platforms, like social media,
    email campaigns, influencer collaborations, and search engine
    optimization. Platforms like Instagram, Facebook, and TikTok enable
    you to reach a large customer base and showcase your products.

    Sending newsletters can be an effective strategy to keep
    your audience and notify them about latest designs, sales, and future events.
    Collaborating with influencers can additionally assist in connecting with
    targeted customers.

    ### Customer Service

    Providing exceptional customer service is vital for establishing a dedicated clientele.
    Make sure that your clients have a great experience from beginning to end.
    Address questions and issues efficiently and courteously.
    Offering convenient exchanges and transparent policies can assist creating
    reliability with your audience.

    ### Analyzing Sales

    Frequently reviewing your performance is crucial to identify areas
    for growth and adjust your {strategies|approaches

  8. tees表示:

    Launching a t-shirt business can be an thrilling venture for entrepreneurs wanting
    to tap into the fashion industry. With a solid plan and dedication, your t-shirt shop can thrive and turn into
    a successful venture. Here are some important steps to keep in mind when starting a t-shirt shop.

    ### Business Plan

    Developing a comprehensive plan is essential for the success and growth
    of your t-shirt shop. This blueprint needs to include the audience, promotional methods, financial plan, and business goals.

    Understanding your customer base will help
    adjust your products and promotional activities
    to suit their preferences.

    ### Design and Production

    Designing of your t-shirts is a key factor in drawing customers.
    Consider hiring experienced designers to develop attractive and trendy designs that
    resonate with your audience. Consider utilizing various printing methods, including screen printing, direct-to-garment printing, and vinyl printing, based on your resources and the quality level of
    the t-shirts.

    ### Sourcing Materials

    Choosing trustworthy vendors for your materials
    is vital to ensure high-quality products.
    Search for suppliers that provide top-notch basic tees in different styles.
    Creating a strong connection with your vendors is important to ensure on-time
    supply and competitive prices.

    ### Building an Online Shop

    In today’s digital era, having an online presence is essential for accessing a wider customer base.
    Create an appealing and efficient online store to display your apparel.
    Use clear pictures and detailed information to provide buyers a
    better understanding of what they are purchasing.
    Look into including elements like secure payment options, ratings,
    and network integration to improve customer interaction.

    ### Promotional Strategies

    Strategic promotion is key to driving customers to your t-shirt shop.
    Use various promotional methods, like social media,
    email campaigns, influencer collaborations, and search engine optimization. Platforms
    like Instagram, Facebook, and TikTok allow you to reach a broad audience and highlight your products.

    Email campaigns is a great way to keep your customers and inform them
    about new arrivals, special offers, and upcoming launches.
    Collaborating with influencers can additionally help in accessing potential clients.

    ### Customer Service

    Providing excellent support is essential for establishing a dedicated customer base.
    Make sure that your clients have a positive interaction from beginning
    to end. Address concerns and issues quickly and professionally.
    Offering hassle-free returns and clear conditions can help building trust with
    your customers.

    ### Assessing Metrics

    Consistently reviewing your business metrics will help identify parts
    for growth and adjust your {strategies|approaches

  9. Are You Using Superb To Bring Traffic For The Website?

    구글상위노출 회사

  10. Cheri表示:

    Guide To Windowdoctor: The Intermediate Guide In Windowdoctor windowdoctor; Cheri,

  11. Всем привет! Подскажите, где найтиразные блоги о недвижимости? Пока нашел https://z-sip.ru

  12. 9 . What Your Parents Taught You About Upvc Windows Near Me upvc windows Near me

  13. Simply wish to say your article is as amazing. The clarity in your post is just nice and i could assume you’re an expert on this subject.
    Well with your permission let me to grab your feed to keep updated with forthcoming post.
    Thanks a million and please continue the rewarding work.

    Here is my site; http://superpremium2.premium4best.eu/

  14. Retrieving what’s yours shouldn’t be troublesome. That’s why our
    service is user-friendly and open.
    Simply give us some basic information, and we’ll handle the rest.

    Don’t allow fraudsters prevent you from your savings. We’re committed to ensure
    the return of every penny.

  15. How To Create Successful Upvc Repairs Near Me Tips From Home Window Repair Near Me

  16. Meds information leaflet. What side effects can this medication cause?
    where can i get generic verapamil prices
    Everything trends of medication. Get information now.

  17. Hey there, I think your website might be having browser compatibility issues.
    When I look at your website in Safari, it looks
    fine but when opening in Internet Explorer,
    it has some overlapping. I just wanted to give you a quick heads up!
    Other then that, wonderful blog!

  18. StephenDeery表示:

    Hello! This post could not be written any better! Reading this post reminds me of my previous room mate! He always kept chatting about this. I will forward this post to him. Pretty sure he will have a good read. Thanks for sharing!
    вавада официальный сайт вход

  19. bokep indo表示:

    My spouse and I stumbled over here from a different website and thought
    I might as well check things out. I like what I see
    so now i’m following you. Look forward to finding out about your web page yet again.

  20. I am regular visitor, how are you everybody? This article posted at this
    web page is genuinely good.

    Also visit my web site lung clear pro reviews

  21. dewa scatter表示:

    What i do not realize is in truth how you’re no longer really a lot
    more well-liked than you may be now. You’re so intelligent.

    You recognize therefore significantly with regards to this topic, made me individually consider
    it from a lot of numerous angles. Its like men and women are not fascinated until it’s one thing to
    accomplish with Woman gaga! Your individual stuffs outstanding.
    All the time care for it up!

  22. Definitely believe that which you said. Your favorite justification appeared to be on the internet the easiest
    thing to be aware of. I say to you, I certainly get annoyed
    while people think about worries that they plainly don’t know about.
    You managed to hit the nail upon the top as well as defined out the
    whole thing without having side-effects , people can take a signal.
    Will probably be back to get more. Thanks

  23. What’s up colleagues, its impressive paragraph concerning cultureand fully explained,
    keep it up all the time.

    Feel free to surf to my web blog :: http://superpremium2.premium4best.eu/

  24. Drugs information leaflet. Generic Name.
    how can i get priligy online
    Actual news about medicament. Get information here.

發佈留言

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