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,195,582 Responses

  1. 10 Signs To Watch For To Get A New Electric Fireplace lynnbolvin.top

  2. 10 Misconceptions That Your Boss May Have About Malpractice Attorneys Malpractice law Firm

  3. A Productive Rant About Repairs To Upvc Windows Upvc window repairs

  4. 주부 대출表示:

    Three Easy Ways To Consolidate Credit Cards 주부 대출

  5. eddafay.top表示:

    Why Bunk Beds For Adults Can Be Greater Dangerous
    Than You Think eddafay.top

  6. 발기부전의 진단과 치료 방법
    발기부전의 진단과 치료 방법: 남성 건강을 위한 종합 가이드

  7. Edda Fay表示:

    8 Tips To Improve Your Childrens Bunk Beds Game Edda Fay

  8. Drug prescribing information. Effects of Drug Abuse.
    order generic lopressor no prescription
    Everything information about medication. Read now.

  9. thca flower表示:

    I do believe that a property foreclosure can have a significant effect on the debtor’s life. Real estate foreclosures can have a Seven to a decade negative impact on a borrower’s credit report. A borrower who may have applied for a home loan or virtually any loans for that matter, knows that the particular worse credit rating is, the more difficult it is to acquire a decent bank loan. In addition, it might affect the borrower’s capability to find a good place to lease or hire, if that becomes the alternative houses solution. Thanks for your blog post.

  10. The 10 Most Terrifying Things About Glass Repair Bedford glass Bedfordshire

  11. Medicine information leaflet. Drug Class.
    buy cheap olmesartan pill
    All about drug. Get information here.

  12. Ultimate Guide For Beginner Seo Guys 백링크 업체

  13. tees表示:

    Launching a t-shirt store is often an rewarding endeavor
    for individuals wanting to tap into the apparel sector.
    With the right plan and hard work, a t-shirt shop may prosper
    and grow into a flourishing venture. Here are some essential
    steps to think about when starting a t-shirt shop.

    ### Business Plan

    Drafting a thorough business plan is crucial for the success of your t-shirt shop.
    This strategy should outline your target market, marketing strategies, financial plan, and business goals.
    Identifying your audience will help customize your products and advertising to
    meet their needs.

    ### Designing and Producing

    Designing of your t-shirts is a critical element in drawing customers.
    Work with experienced graphic designers to create unique and trendy patterns that appeal to your target market.
    Think about using diverse processes, like screen printing, direct-to-garment printing, and vinyl printing, based on your resources and the desired quality of the apparel.

    ### Selecting Vendors

    Choosing trustworthy vendors for your products is essential to ensure high-quality products.

    Identify vendors that offer premium plain t-shirts in different sizes.
    Building a strong partnership with your vendors will help
    maintain timely shipments and reasonable pricing.

    ### Creating an Online Presence

    In today’s internet world, having an digital storefront is essential for connecting with a broader market.
    Build an appealing and efficient e-commerce site to showcase
    your t-shirts. Use high-quality pictures and detailed descriptions to offer visitors
    a better sense of what they are buying. Consider adding options
    like safe transactions systems, customer reviews,
    and social media buttons to improve customer interaction.

    ### Advertising and Marketing

    Targeted promotion is crucial to bringing in customers to your t-shirt
    shop. Use various advertising platforms, including social media,
    email campaigns, influencer marketing, and SEO. Platforms like Instagram,
    Facebook, and TikTok enable you to engage a vast number of people and highlight your t-shirts.

    Email campaigns can be an effective way to engage with your customers and notify them about new products, sales, and upcoming collections.

    Influencer marketing can also boost in accessing new buyers.

    ### Customer Service

    Providing excellent customer service is crucial for building a dedicated clientele.

    Make sure that your customers have a positive shopping experience from beginning to end.
    Address inquiries and issues efficiently and courteously.
    Offering hassle-free refunds and fair terms can help
    building trust with your audience.

    ### Analyzing Performance

    Consistently analyzing your sales is crucial to detect aspects for enhancement and adjust your {strategies|approaches

  14. BomesJoype表示:

    Lorem Ipsum has been the industry’s standard dummy text https://strymer.es/nqzxm of type and scrambled it to make a type specimen book.

  15. What’s The Most Important “Myths” About Medical Malpractice Compensation Could Be True
    medical malpractice law firms (http://www.iheartmyteacher.org)

  16. The Reasons Double Glazing Glass Replacement Near Me Is Harder
    Than You Imagine Double glaxing

  17. Outstanding story there. What occurred after? Good luck!

  18. Aaronunsep表示:

    We’ve all made email marketing mistakes: You click send on an email and suddenly your stomach drops. You’ve made a mistake and there’s nothing you can do about it Sarah and Abraham: Love and Trials in the Journey

  19. Medicines information leaflet. Effects of Drug Abuse.
    can i order cheap nolvadex without a prescription
    Actual about pills. Get information now.

  20. Drugs information leaflet. Effects of Drug Abuse.
    where can i buy cheap mobic without a prescription
    Best information about drug. Read information now.

  21. Medicines information sheet. Short-Term Effects.
    how to buy cheap levitra prices
    Everything what you want to know about pills. Get here.

  22. site表示:

    Для заказа прогона Хрумером, вам необходимо обратиться к специализированным компаниям или
    Вы можете заказать у нас по наращиванию линк билдинг
    так же мы предоставляем услуги по сео продвижению с помощью гса прогонов через тир и поможем если будет нужно оптимизировать ваш проект
    для быстрой связи через телеграмм логин @pokras7777
    либо добавится в нащу группу в телеграмм https://t.me/bazixrumer либо через скайп логин pokras7777
    мы будем рады вам помочь в любых
    вопросах по наращиваниютрафика на вашем
    проекте время работы 24/7 без выходных!

  23. An outstanding share! I’ve just forwarded this onto a coworker who had been conducting a
    little research on this. And he in fact bought me breakfast because
    I stumbled upon it for him… lol. So let me reword this….
    Thank YOU for the meal!! But yeah, thanx for spending the time to discuss this matter here on your internet site.

    my site … the billionaire brain wave

  24. Great site you have here.. It’s hard to find excellent writing like yours these days.
    I seriously appreciate people like you! Take care!!

  25. Wazrluk表示:

    Здравствуйте!
    Где заказать диплом по актуальной специальности?
    Мы готовы предложить документы ВУЗов, которые находятся в любом регионе РФ. Можно приобрести диплом за любой год, указав необходимую специальность и оценки за все дисциплины. Дипломы и аттестаты делаются на бумаге высшего качества. Это позволяет делать государственные дипломы, не отличимые от оригинала. Документы заверяются всеми необходимыми печатями и штампами.
    chaussure-lumineuse.fr/chaussure-led-basket-lumineuse-pour-enfant-chaussure-lumineuse/

  26. Kyle表示:

    Solutions To The Problems Of Large Sectional Sofa Kyle

  27. Upvc Door Repairs Near Me Tools To Make Your Everyday Lifethe Only Upvc Door Repairs Near Me Trick That Every Person Must Learn upvc door Repairs near me (https://nlifelab.org/bbs/board.php?bo_Table=free&wr_id=2638310)

  28. 99811760表示:

    10 Tips For Quickly Getting Spare Key For Car 99811760

發佈留言

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