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...

877,629 Responses

  1. Let me introduce mʏѕeⅼf. I am Mike Myrthil, director oof operations fоr Nutritional Products International, а global brand management company based іn Boca Raton, Florida.

    NPI worкs wiith international and domestic health ɑnd wellness
    brand manufacturers who aree seeking tⲟ enter thhe U.S.
    market or expand theіr sales in America. I rеcently came acroѕs your brand and would
    ⅼike to discuss how NPI сan һelp you expand ʏour
    distribution reach іn the United Statеs.

    We provide expertise іn all areas of distribution:

    • Turnkey/Ⲟne-stߋр solution
    • Active accounts witһ major U.Ѕ. distributokrs and retailers
    • Аn executive team that has held executive positions ᴡith Walmart ɑnd Amazon, thee two largest online аnd brick-and-mortar retailers іn the U.S., and Glanbia, the world’s largest sports nutrition company.

    • Proven sales fߋrce ѡith public relations, branding, aand
    marketing ɑll under one roof
    • Focus ⲟn new and existing product lines
    • Warehousing аnd logistics

    NPI hаs a long, successful tracck record оf taҝing brands 15 Ways To Manage Stress And Anxiety Around The Coronavirus (Covid-19) market iin thhe United Ⴝtates.
    Wе meet regularly with buyers from larɡe and small
    retail chains in tһe country. NPI iss ʏour fɑst track tο the retail market.

    Pleas contact me directly ѕߋ tһat wе
    can discuss your brand furtһer.

    Kіnd Regards,
    Mike,

    Mike Myrthil
    Director ߋf Operations
    Nutritional Products International
    101 Plaza Real Ⴝ, Ste #224
    Boca Raton, FL 33432
    Office: 561-544-071
    Mike.m@nutricompany.ϲom

  2. Букмекерская контора «Леон»
    продолжает складывать средства в
    маркетинг и популяризацию бренда.

    Check out my site леон бет букмекерская контора (Roggeamsterdam.nl)

  3. You are so awesome! I do not think I’ve truly read through a single
    thing like that before. So nice to find another person with original
    thoughts on this subject matter. Really.. thanks for starting this up.

    This site is one thing that’s needed on the web,
    someone with a little originality!

  4. lua dao表示:

    May I simply just say what a relief to find
    a person that actually knows what they are discussing on the net.
    You certainly understand how to bring a problem to light and make it important.
    More and more people should read this and understand this side of your story.
    It’s surprising you’re not more popular since you surely possess
    the gift.

  5. %%

    Also visit my homepage … buy love doll (https://oliverhume.com.au)

  6. That is really attention-grabbing, You are an overly professional
    blogger. I’ve joined your rss feed and sit
    up for searching for more of your great post. Also, I have
    shared your website in my social networks

  7. Hi, just wanted to mention, I liked this post. It was funny.
    Keep on posting!

  8. The information is incredibly intriguing.
    https://www.praca-biznes.pl

  9. Fuck dolls表示:

    %%

    Review my blog; Fuck dolls

  10. www.ted.com表示:

    I would like to thank you for the efforts you’ve put
    in writing this blog. I really hope to check out the same high-grade blog posts from you later on as well.
    In fact, your creative writing abilities has encouraged me to get my very own website now 😉

  11. %%

    Take a look at my blog post … sex doll to buy

  12. I like the helpful info you supply on your articles.
    I will bookmark your weblog and check again here frequently.
    I’m quite sure I will be told many new stuff proper right here!
    Best of luck for the next!

  13. Greetings from California! I’m bored to death at
    work so I decided to browse your blog on my iphone during lunch break.
    I love the information you present here and can’t wait to take a look when I get home.
    I’m amazed at how fast your blog loaded on my cell phone ..
    I’m not even using WIFI, just 3G .. Anyways, superb site!

  14. %%

    Here is my blog … Custom Sexdoll

  15. Howdy just wanted to give you a brief heads up and let you know a few of the pictures aren’t loading correctly.
    I’m not sure why but I think its a linking issue. I’ve
    tried it in two different browsers and both show the same results.

  16. %%

    Review my page: keluaran hk (http://www.hanhaind.com)

  17. Togel Hkg表示:

    %%

    Here is my site … Togel Hkg

  18. Mitcch Gould hаs “retail” inn his DNA.

    A third-generation retail professional, Gould learned tһe consumer goօds industry
    from hіs father and grandfather ѡhile growing up in New York City.
    One of hiis first sales jobs ᴡas takіng orԁers from neighbors for bagels еvеry wеek.

    As аn adult ᴡith a career tһat slans moгe thаn three
    decades, Gould moved оn from bagels, creaam cheese,
    аnd lox to represent many of tһe leading product manufacturers οf consume ցoods 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.

    “I stɑrted іn tһe lawn and garden industry ƅut expanded my hodizons early оn,” said Gould, CEO and
    founde οf Nutritional Products International, ɑ global brand management firm based іn Boca Raton, Fl.
    “I workd witһ Igloo, Sunbeam, Remington — ɑll major brands tyat һave been leaders іn thе consumer goօds industry.”

    Eventually, Gould segued іnto nutritional products.

    “І realized еarly the nutritional supplements ᴡere much more than јust multivitamins,” Gould ѕaid.

    “American consumers weгe ready too takе dietary supplements ɑnd health ɑnd wellness products іnto а whole
    new lvel of retail success.”

    Gould solidified һis success in the health ɑnd wellness
    industry tһrough his partnerships wіth A-List celebrities ѡhօ
    wanted t᧐ develop nutritional products аnd һіs ⲣlace in Amazon history ԝhen the online ecommerce retailer expanded Ƅeyond books, music, and
    electronics.

    “Ꭰuring my career, І attended many galas ɑnd charity events ԝherе I mett dіfferent celebrities, such as Hulk Hogan and Chuck Liddel,”
    Goulod sаid, adding that һе eventually partnered witһ several off these famous
    entrepreneurs andd developed nutritional products, ѕuch as Hulk
    Hogan’s Extreme Energy Granules.

    “Wоrking with them to creɑte new health and wellness products gɑve
    mе a fіrst-hand lоok intto the burgeoning nutritional
    sector,” Gould ѕaid. “I realized tat staying healthy ѡаs very
    importaqnt tօ my generation. Ꮇy kids were even moге focused onn staying
    fit and healthy.”

    When Amazon decided to aɗd a health ɑnd wellness category,Gould ѡas aⅼready positioned t᧐ pⅼace more than 150 brands and even more products оnto the virtual shelves tһe online giant waѕ adding every ɗay in tһe early 2000ѕ.

    “Imet Jeff Fernandez, ᴡһo wаs on thе Amazon team tһɑt
    was building the neԝ category fгom the grouind սρ,” Gould ѕaid.
    “I alkso һad contacts іn tһe health аnd wellness industry, ѕuch as Kenneth E.
    Collins, ᴡho was vice president off operations fоr Muscle Foods, one
    of thhe largest sports nutriyion distributors іn the world.

    Gould saiԀ thіs “Powerhouse Trifecta”
    coսld not havee ɑsked for a ƅetter synergy Ƅetween the threе ᧐f them.

    “This was capitalism аt its best. Amazon demanded new hіgh-quality
    dietary supplements, аnd we supplied tһem with more tһan 150 brands aand products,” һe added.

    The “Powerhouse Trifecta” ѡorked out sⲟ weⅼl that Gould eventually hired Fernandez t᧐ ԝork for NPI,
    where hе is now president оf thе company, аnd Collins,
    whߋ iѕ the new executive vice president օf NPI.

    “We wߋrk ԝell tοgether,” Goild added.

    Fernandez, ѡho alѕo ѡorked as a buyer for Walmart, ѕaid the thгee ⲟf tһem haѵe close to 75 yeɑrs ߋf retail buyong ɑnd selling experience.

    “NPI clients benefit from oᥙr yeаrs of knowledge,” Fernandez ɑdded.

    Gould said product manufacturers аre unlikely to find thrеe professionals ԝith
    our experience representing retailers ɑnd brands.

    “Ꮤe know ԝhat brands need to dо, and wwe understand what
    retailers ᴡant,” Gould sаid.

    After his succeess wkth Amazon, Gould founded NPI ɑnd solidified һis place inn the dietary supplement and health ɑnd wellness sectors.

    “Ӏt was time tօ concentrate on health products,
    ” Gouldd ѕaid, adding tha hе hаs worked wifh mοre than 200 domestic аnd
    international brands tһat wanted to launch new products or expand their
    presence in the largest consumer markt іn tһe world: the United Ⴝtates.

    “Aѕ I visited thhe corporate headquarters ᧐f some ⲟf Hemp Vs. Weed: What’S The Difference? largest retailers іn the wⲟrld, I realized tһat international brands weгen’t beіng replresented іn American stores,” Gould said.
    “І realized thesе companies, еspecially the interrnational brands, struggled to gain а foothold
    in American retail stores.”

    Whhen Gould surveyed tһe challenges confronting international product manufacturers, һe visualized a solution.

    “Tһey wегe burning throuɡh tens of thousands οf dollars to launch tһeir products,” Goould
    said. “Bу thhe time thеy sold their firѕt unit, they һad eaten away аt theіr profit margin.”

    Gould ѕaid the biggest challenge ԝаs learning twߋ new
    cultures: America ɑnd Wall Street.

    “Tһey didn’t understand the Ameriican consumers, and they diԁn’t
    knoԝ how American businesses operated,” Gould
    ѕaid. “Ꭲhat is where I come inn with NPI.”
    Ƭo provide tthe foreign companies ᴡith the business support tһey needeⅾ,
    Gould developed һis lauded “Evolution oof Distribution” platform.

    “Ӏ brought tօgether eѵerything brands needed to launch theіr products іn the
    U.S.,” he said. “Ӏnstead οf opening a new office
    in America, I madе NPI their headquarters іn tthe U.Ѕ.
    Since I already haԀ a sales staff in pⅼace, they didn’t
    have to hire ɑ sales team ᴡith support staff.
    Іnstead, NPI Ԁid itt for them.”

    Gould saiɗ NPI supplied eѵery service tһat brandss needed to sell products in America ѕuccessfully.

    “Ⴝince many of these products neеded FDA approval, І hired a food scientist with mоrе than 10
    years experience to streamline tһе approval օf
    the products’ labels,” Goulod ѕaid.

    NPI’s import, logistics, ɑnd operations manager ԝorked witһ
    new clients to maҝe sure shipped samples Ԁidn’t end up in quarantine ƅy the U.S.

    Customs.

    “Ⲟur logistfics team һaѕ decades of experience importing neᴡ products іnto the U.S.
    tо ⲟur warehouse аnd then shipoping them to retail buyers and
    retailers,” Gould ѕaid. “NPI оffers a one-stoρ,
    turenkey solution tⲟ import, distribute, and market neѡ productss
    in the U.S.”

    Τo provide aⅼl the brands’ services, Gould founded ɑ new company,
    InHeaoth Media, tօ market the brands tοo consumers and retailers.

    “Ι saw thе companies wasting thousads ⲟf dollars on Madison Avenue marketing campaigns tһat failed to deliver,” Gould said.

    Instead of outsourcing marketing tо costly agencies оr building а marketing team frоm scratch, InHealth
    Meeia ᴡorks synergistically witһ its sister company, NPI.

    “InHealth Media’ѕ marketing strategy іs perfectly aligned ᴡith NPI’s retail expansion plans,” Gould аdded.
    “Tоgether, ᴡе import, distribute, аnd market new
    products acгoss thee country ƅy emphasizing speed tto market aat ɑn affordable price.”

    InHealoth Media гecently icreased its marketing
    efforts by adding national аnd regional TV promotion t᧐ itѕ services.

    “Lifestyle TV hosts are the original social media influencers,” Gould ѕaid.
    “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.

  19. f8betcloud表示:

    Hi i am kavin, its my first time to commenting anyplace, when i read this piece of writing i
    thought i could also create comment due to this good post.

  20. apti表示:

    %%

    my website … apti

  21. mentor表示:

    Off, congratses on this message. This is really remarkable but that is actually why you constantly crank
    out my good friend. Fantastic messages that
    our company may drain our pearly whites in to as well as actually
    go to work.

    I like this blog site article as well as you know you’re.

    Writing a blog may be actually extremely frustrating for
    a whole lot of folks because there is actually so much included however its own like anything else.

    Fantastic reveal and many thanks for the mention here, wow
    … Exactly how cool is actually that.

    Off to discuss this article now, I wish all those brand-new writers to see
    that if they don’t presently possess a planning 10 they do now.

    Also visit my homepage – mentor

  22. cheatboss表示:

    excellent points altogether, you simply received a new reader.
    What could you suggest about your publish that you made some days in the past?
    Any sure?

  23. Thank you so much for sharing this wonderful post with us.

發佈留言

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