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,123,627 Responses

  1. WilliamSoorp表示:

    http://medicinefromindia.store/# top online pharmacy india

  2. WilliamSoorp表示:

    http://certifiedpharmacymexico.pro/# mexico drug stores pharmacies

  3. Eugenehaupe表示:

    buy prescription drugs generic cialis without a doctor prescription non prescription erection pills

  4. ledger live表示:

    I love your blog.. very nice colors & theme.
    Did you create this website yourself or did you hire
    someone to do it for you? Plz answer back as I’m looking to construct my own blog and would like to
    know where u got this from. cheers

  5. Our complete information of immigration laws, visa processing requirements and procedures, our extensive expertise having processed more
    visas from Thailand to the United States than all other firms mixed, the fact that we are Thailand’s First.

    Look at my web page; UK Immigration Lawyer;
    watsonpainting.com,

  6. cockrider表示:

    Good аnswer bacck in гetuгn of tyis matter with firm arguments and telling all аbout that.

  7. I visited a lot of website but I conceive this one holds something special in it.

    Feel free to visit my blog post; toyota of denton

  8. BennyNib表示:

    canadian pharmacy 24h com: northern pharmacy canada – canadianpharmacyworld

  9. WilliamPaw表示:

    http://medicinefromindia.store/# buy medicines online in india

  10. Ded表示:

    Besides video poker and blackjack, Real Money Action will provide a full assessment of all other table games: roulette, baccarat, craps, and the various games based on poker. These games do not require skill but rely on luck. In casinos, if a game is based purely on luck, then the gambler can expect to face a higher house edge. In each case, I’ll discuss the positive and negative aspects of the game. When playing for real money, you need to know which games to seek out and which ones to avoid. Often, it’s not that simple, because certain rules change the expected return of a game significantly. At Planet 7, players get exclusive access to the best online casino games for real money, 24 hours a day. We want you and your bankroll to shine, which is why you can always rely on us to bring you 5-star service, light-speed transaction times, and real money casino bonus offers that can be redeemed on hundreds of online slots, blackjack, roulette, video poker, craps games, and more.
    http://romeo-wiki.win/index.php?title=Casino_europei_aams_online
    First up Roulette. The image above is a screenshot of the live table I chose. There is also an option to see it in ‘HQ’ which I only noticed later on, it didn’t improve the quality that much for me to be honest. You can type in the chat and the dealer will talk back to you. I’m sure many guys are happy to talk to her – especially as she giggles and wafts her hair! Quite entertaining. Playing the game is easy. It’s all very simple to use really much like normal roulette. I stuck around for a while and really enjoyed it, even managed to finish up a few quid! Paddy Power is an online gambling operator that needs no introduction. Its large presence in the UK, both with land-based stores and online products for sports betting and casino games, make it one of the best known brands in the industry. This translates into top products and professional services and when it comes to the Paddy Power Casino, no corners were cut on the road to offer a premium option for all players. Winner of the Casino Operator of the Year title in 2015 at the EGR Awards, there is no doubt that quality is at a very high level.

  11. Hi there, the whole thing is going perfectly here and ofcourse every one is
    sharing information, that’s really excellent, keep up writing.

  12. Syair HK表示:

    I am genuinely happy to read this web site posts which contains lots of valuable information, thanks for providing such information.

  13. Fantastic beat ! I wish to apprentice at the same time as you amend your website,
    how could i subscribe for a blog site? The account aided me a appropriate deal.
    I were tiny bit familiar of this your broadcast provided vivid transparent idea

  14. Eugenehaupe表示:

    canada pharmacy reviews best canadian pharmacy online trustworthy canadian pharmacy

  15. An intriguing discussion is worth comment. There’s no doubt that that you need to publish more on this issue, it may not be a taboo matter
    but usually folks don’t speak about such issues.

    To the next! Many thanks!!

  16. BennyNib表示:

    п»їlegitimate online pharmacies india: world pharmacy india – Online medicine order

  17. WilliamPaw表示:

    https://medicinefromindia.store/# indian pharmacy online

  18. Ded表示:

    Disinfectant is used to clean the property; commonly-touched surfaces are cleaned with disinfectant between stays; bed sheets and towels are laundered at a temperature of at least 60°C 140°F. Check out our great room packages available. Palms Casino Resort 4321 W. Flamingo Road Las Vegas, NV 89103 Unplug completely with our signature services at The Spa at Palms. Start enjoying the full range of amenities and benefits that Pechanga has to offer simply by using your Club card. You may also receive invitations to special events and promotional offers. Check your balances, available offers, tier status and more when you login. Not yet an Ocean Rewards Member? Get in on the thrill with exciting perks, benefits and the ultimate VIP treatment when you sign up. Tachi Palace Casino Resort offers the best of both worlds — everything you need and expect at a California casino getaway in a beautiful, more quiet location.
    https://claudiaroche.com/free-spins-casino/
    It is common practice for online casino apps to offer refer-a-friend programs. Simply put, users can receive a referral bonus if they are able to get their friends to sign up for that same casino app. Additionally, these programs will also pay out the new user in that same referral bonus. This specific type of bonus can reward players in extra bonus cash, or in free spins. Before you do this, be sure to read the terms and conditions as you may need to use a specific, unique link to get casino credits for your referral. The answer to this is “Yes, it is.” Everything you see on our site marked as a no deposit bonus or free play bonus is free money, and it requires no deposit whatsoever in order to use the bonus and play for free. Some of the bonuses will be added to your account automatically, while some will require a bonus code or contacting customer support, but once you’re found eligible for it, the selected bonus will be awarded to your account as real play casino balance, and you’ll be able to enjoy it completely free of charge.

  19. Ded表示:

    Miami Club Casino is powered by WGS Technology’s browser-based software. Also known as Vegas Technology, it is known for developing games with splendid graphics, smooth game play, great animations, and realistic audio effects. One of the best bonuses that players can claim at Miami Club Casino is the Daily Deposit Bonus. On any day, players can get a 20% to 45% match bonus. The amount of the match is dependent on your VIP player club level, and the minimum deposit to qualify is $25. You’ll find three versions of Miami Club casino — download, Flash, and mobile casino. TOGG’dan ‘teknoloji’sürprizi:2023’te yollara çıkması beklenen Türkiye’nin otomobili Togg’un CEO’su Gürcan Karakaş, lansmanı yapılacak ilk ürünün otomobil olmayacağını bildirdi. Karakaş, ‘Şu ana kadar…
    https://remingtonljvw629630.thezenweb.com/online-%CF%84%CF%85%CF%87%CE%B5%CF%81%CE%B1-%CF%80%CE%B1%CE%B9%CF%87%CE%BD%CE%B9%CE%B4%CE%B9%CE%B1-%CE%9C%CE%B5%CE%B8%CE%BF%CE%B4%CE%BF%CE%B9-%CE%9A%CE%B1%CF%84%CE%B1%CE%B8%CE%B5%CF%83%CE%B7%CF%82-57222527
    To play Chumba Casino games, you need to be a US resident who does not live in the two restricted states of Idaho and Washington. Chumba Casino forms part of the sweepstakes and social casino model which does not fall under the legislation of real money casinos. Whether it’s the High5 Casino social casino promo code or the Chumba Casino bonus that we’ve been discussing in this article, players are always going to have doubts. Our aim is to give you as much detail as possible about the Chumba Casino bonus, which is why our experts have provided you with answers to the top five most frequently asked questions about the offer. This website is using a security service to protect itself from online attacks. The action you just performed triggered the security solution. There are several actions that could trigger this block including submitting a certain word or phrase, a SQL command or malformed data.

  20. Keep on working, great job!

  21. WilliamSoorp表示:

    http://medicinefromindia.store/# online shopping pharmacy india

  22. I like what you guys are usually up too. This kind of clever
    work and exposure! Keep up the terrific works guys I’ve added you guys to my
    blogroll.

  23. Eugenehaupe表示:

    top 10 pharmacies in india world pharmacy india indian pharmacies safe

  24. read more表示:

    Definitely believe that which you stated. Your favorite justification appeared to be on the
    web the simplest thing to be aware of. I say to you, I
    certainly get irked while people think about worries that they just
    do not know about. You managed to hit the nail upon the top and
    also defined out the whole thing without having
    side effect , people could take a signal.
    Will likely be back to get more. Thanks

  25. WilliamPaw表示:

    https://medicinefromindia.store/# top online pharmacy india

  26. ClintonKaf表示:

    Fences of use multiple purposes, beginning from providing safe keeping and private to enhancing the belle of a property. Yet, like any make-up, fences require maintenance, occasional repairs, and sometimes unvaried replacement to ensure they carry on with to fulfill their intended functions. In this write-up, we’ll delve into the conflicting services offered about skilled impartial companies, including shape, institution, and replacement.

    Wall Mend Services:
    All over time, fences can suffer harm proper to weather hazard, aging, or unpremeditated damage. Unrefined issues encompass warped or rotted wood, bias posts, broken panels, flowing arms, and rusted metal components. Maven bound mend services address these issues promptly to reimburse the non-partisan’s structural virtue and appearance. Skilled technicians assess the indemnity, persuade acceptable repairs, and efficiently effect out the necessary work, whether it involves replacing damaged sections, reinforcing rickety spots, or fixing hardware. Past addressing issues near the start, sidestep renewal services improve string out the lifespan of the uncertain and ban more widespread damage.
    fence replacement

    Fence Station Services:
    Whether you’re installing a fresh neutral instead of gage, privacy, or aesthetic reasons, wizard rampart fitting services certify a hassle-free procedure from start to finish. These services typically on with a consultation to about the client’s needs, preferences, and mark specifications. Based on this information, experts recommend fitting enclosure materials, styles, and designs that crew the assets’s architecture and make the acquaintance of the desired functionality. Able installers treat all aspects of the installation, from milieu preparation and post setting to panel or picket placement and final adjustments. By entrusting the province to knowing professionals, assets owners can expect a durable, decorously installed unprejudiced that enhances restraint lure and fortune value.

    Stonewall Replacement Services:
    When a bound reaches the put to death of its lifespan or sustains irreparable hurt, replacement may be the most practical solution. Confine replacement services concern removing the existing hedge and installing a new inseparable tailored to the client’s preferences and property requirements. Professional confine companies offer a broad line of fencing materials, including wood, vinyl, aluminum, chain-link, and composite options, allowing feature owners to settle upon the most opportune choice based on durability, upkeep requirements, and budget. With punctilious attention to in depth and status craftsmanship, impartial replacement services insure a seamless transformation to a recent, sound keep that meets the worth’s needs and enhances its appeal.

    Conclusion:
    From repairing slight damages to installing virgin fences and replacing worn-out structures, experienced uncertain services engage a vital place in maintaining the functionality, appearance, and value of residential and commercial properties. Away partnering with wise professionals, means owners can fancy peacefulness of do not think twice about knowing that their fencing needs are in competent hands, ensuring long-lasting, attracting fences that be in the service of their intended purposes effectively.

  27. WilliamPaw表示:

    http://medicinefromindia.store/# cheapest online pharmacy india

  28. I’m no longer positive wheгe you’re getting your information, howeνer good topiⅽ.
    I needs to spend some time studying mսch more or undersanding more.
    Thank yօu for wonderful info I useⅾ to be searching for this
    informаtion for my mission.

  29. japan evisa表示:

    Highly descriptive blog, I enjoyed that bit.
    Will there be a part 2?

  30. What’s up friends, how is everything, and what you wish for to say about this
    post, in my view its actually amazing in support of me.

發佈留言

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