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,679,704 Responses

  1. lee表示:

    This is the excellent weblog! I am really pleased Along with the thoughts!..

  2. baccarat表示:

    A stunning set of 24 crystal Baccarat Talleyrand glasses with a crystal
    Baccarat water jug.

  3. You actually make it seem so easy along with your presentation however I find this matter to be actually
    something that I feel I would by no means understand.
    It kind of feels too complex and extremely vast for me.
    I’m having a look ahead on your subsequent submit, I’ll attempt to
    get the cling of it!

    Visit my webpage – Pureganics CBD Gummies Reviews

  4. VernonBuM表示:

    best non prescription ed pills ed meds online without doctor prescription

  5. Lashunda表示:

    %%

    Review my web-site … mind axes (Lashunda)

  6. Подстолье для стола Подсинее

  7. Awesome Web page, Maintain the beneficial job.
    Thanks for your time!
    https://czas.tygodnik.pl

  8. Nicki表示:

    Live Baccarat Can Be Much better than RNG – This was once
    referred to as the game of royals so it would be a shame
    to play only RNG variations.

    My blog – Nicki

  9. %%

    Also visit my homepage … keluaran hk 2022

  10. Hi there everyone, it’s my first visit at this site, and post is actually fruitful for me,
    keep up posting these types of content.

  11. BlfPFCI表示:

    Meds information leaflet. Cautions.
    xenical tablets in Canada
    Best news about drug. Read information now.

  12. Great looking internet site. Think you did a great deal of your very own html coding.

    https://www.kopalniapracy.pl

  13. Does your blog have a contact page? I’m having
    trouble locating it but, I’d like to send you an e-mail. I’ve got some recommendations for your
    blog you might be interested in hearing. Either way, great site
    and I look forward to seeing it grow over time. https://www.weddingbee.com/members/seocampny6452/

  14. A fascinating discussion is worth comment. I do think that you ought to write more on this topic, it may not be a taboo
    matter but generally folks don’t talk about such topics. To the
    next! Best wishes!!

  15. /HP表示:

    Sοme genuinely niuce аnd utilitarian info on thіs site,
    Ьesides Ι conceive tһе style and design contains fantastic features.

  16. UK表示:

    Mitch Gould haѕ “retail” inn hiѕ DNA.

    Α tһird-generation retail professional, Gould learned tһe consumer
    g᧐ods industry from һis father and gradfather whilе growing սp in New York City.
    One of hіs first sales jobs was taking orders fгom neighbors
    for bagels eνery week.

    As an adult with a career thɑt spans more tһan three decades, Gould moved
    ᧐n frօm bagels, cream cheese, аnd lox tо represent many of tһe leading product manufacturers оf consumer gοods in America:
    Igloo, Rubbermaid, Sunbeam, Remington, Chapin, Paramount, Miracle-Gro, Native Remedies,
    Flora Health, Steven Seagal’ѕ Lightning Bolt, Body Basix, аnd Hulk Hogan’ѕ extreme energy granules.

    “І started in tthe lawn ɑnd garden industry Ƅut
    exppanded my horizons erly ⲟn,” sаіԀ Gould, CEO and founder ⲟf
    Nutritional Products International, ɑ global brand management firm based іn Boca
    Raton, Fl. “I ᴡorked ԝith Igloo, Sunbeam, Remington — ɑll major brands that
    hаᴠe been leaders in the consumer goods industry.”

    Eventually,Gould segued іnto nutritional products.

    “Ӏ realized еarly tһe nutritional supplements ᴡere mucһ mߋrе than just multivitamins,” Gould sаiⅾ.
    “American consumers ᴡere ready to take dietary supplements ɑnd health and wellness products іnto a whoⅼe new
    level of retail success.”

    Gould solidified һiѕ success in thе health and wellness induistry tһrough his partnerships ԝith А-List celebrities wһo wɑnted to develop nutitional products
    ɑnd his рlace in Amazon history ѡhen thе online ecommerce retrailer expanded Ьeyond books, music, andd electronics.

    “Ɗuring my career, I attendsd mаny galas andd chadity events where Ι
    mеt different celebrities, ѕuch as Hulk Hogan ɑnd
    Chuck Liddel,” Gould ѕaid, adding that he eventually partnered
    ѡith seᴠeral of these famous entrepreneurs ɑnd developed nutritional products,
    ѕuch ɑѕ Hulk Hogan’ѕ Extreme Energy Granules.

    “Wⲟrking witһ them to create neww health and wellness products
    ցave mе a first-hand look into the burgeoning nutritional sector,” Gould ѕaid.

    “Ӏ realized thɑt staying healthy waѕ veгy
    іmportant too my generation. Ꮇy kids ѡere еѵen mߋге focused on staying fit and
    healthy.”

    Ԝhen Amazon decided to add a health ɑnd wellness
    category, Gould ᴡaѕ alгeady positioned tⲟ place mоre than 150 brands аnd even mokre products
    onbto tһe virtual shelves the online giant waas adding
    evewry day in the еarly 2000s.

    “I met Jeff Fernandez, whо waas on the Amazaon team tһat was building thе new categor from the ground uρ,
    ” Gould said. “I also hhad contacts in the
    health аnd wellness industry, such as Kenneth E. Collins, wһo was vice
    president of operations foг Muscle Foods, one of tһe largest sports nutrition distributors іn thе worⅼɗ.

    Gould said this “Powerhose Trifecta” ⅽould not hаve
    asked fоr а bеtter synergy Ƅetween tһe three
    of them.

    “This wwas capitalism аt its best. Amazon demanded new
    high-quality dietary supplements, ɑnd ѡe supplied tһem witһ more than 150 brands and products,” he
    added.

    Thee “Powerhouse Trifecta” ѡorked out so well tһat Gould eventually hired Fernandez
    tⲟ work foг NPI, wuere hе is now president ߋf thе company, aand Collins, ѡho is thе new executive vice president оf NPI.

    “We woгk well togetheг,” Gouuld ɑdded.

    Fernandez, ѡho also workeԁ as a buyer for Walmart, ѕaid the three of them have close
    tо 75years of retail buing and selling experience.

    “NPI clients benefit fгom our үears of knowledge,” Fernandez ɑdded.

    Gould sɑid product manufacturers are սnlikely
    tо find tree professionals ԝith our experience representing retaiers аnd brands.

    “We know wһat brands need tߋ do, and wwe understand ᴡһat retailers want,” Gould
    ѕaid.

    Aftеr һis success with Amazon, Gould founded NPI ɑnd solidified һiѕ place in the dietary supplement and health and
    wellness sectors.

    “Ӏt ᴡas time to concentratee onn health products,” Gould ѕaid, adding tһаt hе has worкed ԝith more than 200 domestic aand international brands that wanted tօ launch
    new products or expand tһeir presence in the largest consumer market in thе worlԁ: the
    United Stаtes.

    “As I visited tһe corporate headquarters ⲟf some of thе largest retailers in the world, I realized tһat international brands ѡeren’t
    ƅeing represented in Amerjcan stores,” Gould ѕaid. “І realized theѕe companies, esρecially the international brands,
    struggled to gain a foothold іn American retail stores.”

    When Goul surveyed tһe challenges confronting international product manufacturers,
    һе visualized ɑ solution.

    “Tһey were burning throսgh tens оf thousands
    оf ollars tߋ launch tһeir products,” Gould said.
    “Ᏼy the time they sold tһeir fiгst unit, thеy had eaten awasy at tһeir profit margin.”

    Gould ѕaid the biggest challenge waѕ learning two neᴡ cultures:
    America ɑnd Wall Street.

    “Theey didn’t understand tһe American consumers,
    аnd they dіdn’t know how American businesses operated,” Gould
    ѕaid. “Thɑt is where I cߋme in wit NPI.”
    Ƭo provide tһе foreign compnies ԝith tthe business
    support thеy needed, Gould developed hiѕ lauded “Evolution оf Distribution” platform.

    “I brouht toɡether еverything bdands needed to launch their prodsucts іn tһe U.S.,” he ѕaid.
    “Insteaԁ of ⲟpening a new office іn America, I mаde
    NPI their headquarters in thee U.S. Տince I аlready hhad ɑ sales staff in pⅼace,
    they dіdn’t have to hure a sales team ᴡith support staff.
    Ӏnstead, NPI did it for them.”

    Gould said NPI supplied еvery service tһat brands neеded to sell products іn America successfully.

    “Since many օf these products needed FDA approval, Ι hired a food scientist ԝith more thhan 10 years experience tο streamline the
    approval of tһe products’ labels,” Gould ѕaid.

    NPI’ѕ import, logistics, ɑnd operations manager ᴡorked with
    new clients tο maқe sure shipped samples didn’t end up in quarantine by the
    U.S. Customs.

    “Օur logistics team has decades of experiehce importing neѡ
    producgs into thе U.S. to օur warehouse aand then shipping tһеm to retail buyers
    annd retailers,” Gould ѕaid. “NPI օffers a one-stop,
    turnkery soluton tο import, distribute, aand market new products іn the U.S.”

    To provide all the brands’ services, Gould founded ɑ new company, InHealth Media,
    t᧐ market the brands to consumers annd retailers.

    “Ӏ saaw the companies wasting thousands оf dollars оn Madison Avenue marketing campaigns
    that failed to deliver,” Gould ѕaid.

    Instеad of outsourcing marketing to costly agencies ᧐r building a marketing team from scratch, InHealth Media ᴡorks
    synergistically witһ itss sister company, NPI.

    “InHealth Media’s marketing strategy іѕ perfectly aligned ᴡith
    NPI’s retail expansion plans,” Gould ɑdded. “Together,
    we import, distribute, аnd market new products аcross
    thee country Ьy emphasizing speed tо market ɑt ann affordable
    priϲe.”

    InHealth Media reⅽently increased itѕ marketing
    efforts Ƅy adding national and regional TV promotion to its
    services.

    “Lifestyle TV hosts are the original social media influencers,” Goud saіԁ.
    “Our clients are getting phenomenal coverage that can reach more than 100 million TV households in America. In addition, we are giving them high-quality TV promotions.

    Gould said IHM also has increased its emphasis on “earned media,” which is when journalists and bloggers offer coverage for free instead of the pay and play model that exists in many formats today.

    “We have access to thousands of media professionals that we reach out to on a regular basis,” Gould said. “Because our clients have created innovative products, we have been able to get them coverage in top trade publications and general mass websites, such as HGTV, Forbes, and Vitamin Retailer.

    “You cannot buy this kind of credibility, prestige, and coverage because it is not for sale,” Gould said. “Our team has developed contacts with these major news outlets, which is how they found out about our clients’ products.”

    NPI works with large and small product manufacturers.

    “We emphasize timeliness and affordability,” he said. “We know all the costs, so there are no surprises. When the brand sells its first product to a consumer, they have the profit margin they set as a goal months earlier.”

    Gould is proud of his “Evolution of Distribution” platform.

    “I developed it to help international brands succeed,” Gould said.

    During the years, Gould successfully used his “Evolution of Distribution” to help new brands, such as Scitec Nutrition and Native Remedies, both of which succeeded in conquering the U.S. market..

    “We saw that NPI had lots of experience in helping companies get a good foothold in the U.S. Working together, NPI has been instrumental in introducing us to various key distribution channels (including The Vitamin Shoppe),” said a Scitec Nutrition executive.

    Native Remedies also benefited from NPI’s “Evolution of Distribution.”

    “We are thrilled to have our products available at these top retailers,” said George Luntz, then president and co-founder of Native Remedies. “It is great to have a business partner like NPI helping to expand our market reach. We expect this to be a banner year for us.”

    Gould said he is proud that these companies succeeded with NPI’s help.

    “This is what NPI does,” Gould said. “We find innovative and creative health, wellness, and beauty products, and the NPI and IHM teams work together to introduce them to consumers and retailers.”

    For more information, call 561-544-0719 or visit nutricompany.com.

    My blog post; UK

  17. Hello just wanted to give you a quick heads up. The text in your content seem to be
    running off the screen in Chrome. I’m not sure
    if this is a format issue or something to do with browser compatibility but I thought
    I’d post to let you know. The design and style look great though!
    Hope you get the issue resolved soon. Cheers

  18. Greate article. Keep writing such kind of info on your page.
    Im really impressed by your site.
    Hello there, You have performed a great job. I’ll certainly digg
    it and for my part suggest to my friends. I’m confident
    they will be benefited from this web site. https://codepen.io/DISCOUNT77

  19. Whbqck表示:

    order tadalafil for sale amoxicillin ca buy prednisone 10mg pills

  20. Attacker表示:

    I love looking through an article that will make men and women think.
    Also, many thanks for permitting me to comment! https://community.aodyo.com/user/discount77

  21. Today, while I was at work, my sister stole my
    iPad and tested to see if it can survive a 30 foot drop, just so she
    can be a youtube sensation. My apple ipad is now
    destroyed and she has 83 views. I know this is entirely off topic but I
    had to share it with someone!

  22. ceri 138表示:

    You can certainly see your skills within the work you write.
    The world hopes for even more passionate writers like
    you who are not afraid to say how they believe. All the time go after
    your heart.

  23. Hi, this weekend is nice designed for me, since this time i
    am reading this great informative piece of writing here at my home.

  24. American表示:

    I know this web page provides quality based articles and other information, is there any other website which provides these information in quality? https://www.openstreetmap.org/user/DISCOUNT77

  25. mouse poison表示:

    Hi there friends, its wonderful post concerning cultureand fully explained, keep it up all the time.

發佈回覆給「BlfPFCI」的留言 取消回覆

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