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,673,947 Responses

  1. Gregoryron表示:

    olympe casino cresus: olympe casino – casino olympe

  2. What i do not realize is if truth be told how you’re no longer really much more
    neatly-favored than you may be now. You’re very intelligent.

    You know thus significantly on the subject of this topic,
    made me in my view consider it from a lot of varied
    angles. Its like women and men are not fascinated until it’s something to accomplish with Woman gaga!
    Your individual stuffs nice. All the time handle it up!

  3. услуги по продаже аккаунтов https://marketplace-akkauntov-top.ru

  4. Gregoryron表示:

    olympe casino avis: olympe casino – olympe casino

  5. It is highly anabolic and has a low androgenic ranking, which means it might possibly help you build muscle with out causing a lot of undesirable unwanted facet effects. It is also known for its capability to increase protein synthesis, which is important for muscle growth. The downside to using Anavar repeatedly is that we see testosterone suppression exacerbated and LDL cholesterol levels remain elevated for a sustained time period. Consequently, a person’s natural testosterone manufacturing will take longer to get well when finally coming off Anavar.
    Nonetheless, we discover it also has a dramatic effect on adenosine triphosphate production and creatine content material contained in the muscle cell. Greater levels of ATP are beneficial for individuals wanting enhanced power when bulking. It can additionally be advantageous for users who are slicing and susceptible to losing strength because of extended restriction of energy. Dianabol is mostly thought of higher for bulking as a outcome of its potent anabolic properties, selling significant muscle mass and energy gains. If you wish to achieve muscle mass shortly and don’t thoughts the danger of unwanted aspect effects, Dianabol may be the higher possibility. Nonetheless, if you need to decrease the risk of unwanted effects, Anavar could additionally be a higher option.
    Nonetheless, it’s not merely energy and endurance athletes that may benefit from Anavar, with some sprinters, swimmers, and boxers additionally utilizing Anavar to gain a competitive edge. Masculinization remains to be potential if doses greater than 10 mg a day are utilized. Studies have reported women experiencing virilization results when receiving excessive doses of 0.a hundred twenty five mg per kg (13) constantly for a yr. Anavar is a spinoff of dihydrotestosterone; thus, there is no conversion to DHT by way of the 5-alpha reductase enzyme. Consequently, Anavar has gentle androgenic properties and unwanted facet effects. We have had patients report important power results on Anavar, even when consuming low energy. This can additionally be why powerlifters often administer Anavar prior to a contest for max strength with out vital weight gain.
    Dianabol, also recognized as Methandrostenolone or Methandienone, is an anabolic steroid used to increase muscle mass and power. It was first developed in Germany in the 1950s and is considered one of the most generally used steroids today. Stacking Dianabol with Anavar will enhance lean muscle mass while decreasing subcutaneous fats mass. Trenbolone operates in a fashion that is significantly distinct from Dianabol, as it does not aromatize or induce water retention. Consequently, we observe less general weight acquire when utilizing trenbolone. Despite this, trenbolone’s capability to reinforce the physique with lean muscle tissue is corresponding to that of Dianabol. You know, anabolic steroids like Dianabol and Anavar are incredibly well-liked amongst bodybuilders and athletes looking to gain a aggressive edge.
    Notably, it fans the metabolic flames, carving coveted physiques with diminished fatty veils. The final family in the anabolic steroid household tree is Nandrolone (19-Nortestosterone) and 19-Nortestosterone derivatives. “After 1935 the most effective methodology of discovering and measuring the protein-building motion of androgenic steroids in humans proved to be metabolic steadiness research. The next household within the anabolic steroid family tree is Dihydrotestosterone (DHT) and DHT derivatives.
    When you are taking it, you will enhance your body’s capability to provide red blood cells, guaranteeing that your purple blood cell count is maintained and facial hair development is averted. That’s because increased levels of testosterone coursing by way of your body while you’re training will give you more calcium inside your muscle cells. This will enhance the force of your muscular contractions, resulting in 30 % more energy. If you’re a beginner, I’ll explain every little thing you want to know, so as to pack on muscle without risking your well being with illegal steroids, however selecting authorized alternate options as a substitute. Yes, Dianabol is available in oral form and is usually taken as a pill.
    Or you presumably can go for anvarol which isn’t solely a safe and authorized alternative; but additionally less expensive than oxandrolone. However, Anavar reverses this effect and will increase muscle-building, due to its anabolic properties; making you look jacked as it will increase glycogen storage in your muscles. Another highly effective impact of artificial testosterone is that it will help you to remain out of a catabolic state after your exercise, which is essential for preserving muscle tissue. Typically you may be in a muscle-depleting state instantly after a heavy weights exercise. Artificial testosterone is a man-made version of testosterone, your body’s strongest anabolic hormone. Since Dianabol is an oral steroid, it can put a pressure on your liver. Incorporating liver help dietary supplements like milk thistle, N-acetyl-cysteine (NAC), or liv.52 might help defend your liver from potential damage.
    Anavar is an oral anabolic steroid, which is an artificial model of the hormone testosterone. It was first developed in the early Sixties by Searle Laboratories and has been used for medical purposes ever since. It is commonly prescribed to deal with muscle losing illnesses corresponding to HIV/AIDS and most cancers. While Methandienone is used for its performance-enhancing advantages, it can be safely utilized for correct use. Nonetheless, improper use of this steroid might end in side effects. Therefore, it’s imperative to hunt recommendation from a medical skilled before initiating Anavar use to ensure its protected and applicable usage. Nonetheless, with regard to lean muscle features, if the person continues to coach exhausting after their cycle and runs a enough PCT (as outlined above), they want to be able to retain nearly all of their gains.
    Total, Nandrolone is much less androgenic and estrogenic than Testosterone. Nandrolone can additionally be mildly estrogenic on its own through its capacity to act as an Estrogen receptor alpha (ERα) agonist [R]. They are very anabolic, however additionally they exhibit significant amounts of satellite tv for pc interaction with other receptors in the physique. There are quite a quantity of 19-Nors which have been synthesized and documented over time, most of which are historically used at low dosages in women’s birth control. For example, Nandrolone is 5α-reduced into DHN, a a lot less androgenic metabolite, and it additionally interacts with Progesterone receptors within the body which may have an anti-androgenic effect on the body.
    Whereas Steroids will bind to all the Androgen receptors in the body, including ones we are not wanting for such as the Prostate, SARMs will solely bind to Androgen receptors within the muscle and bone. Chromium to make you extra insulin sensitive, Carnitine to assist your metabolism, and numerous others to help your fat loss endeavors. WIN-MAX is designed by CrazyBulk as a substitute, combining high quality components that can assist you lose fat and doubtlessly even gain muscle as well.
    However, if a person predominantly needs to burn fat on Anavar, then a small calorie deficit can be carried out to accelerate fat loss whereas aiding muscle retention. Cardiovascular train, or HIIT (high-intensity interval training), may also be utilized to speed up a user’s metabolism whereas providing cardiac benefits. The main function of post-cycle therapy is to restart endogenous testosterone manufacturing. This aids in normalizing hormone levels for optimum physiological and psychological well being, in addition to retaining outcomes from a cycle. Finasteride (Propecia) is an FDA-approved medication shown to be effective at blocking DHT ranges within the body and reducing hair loss (19). However, studies show that roughly 52% of males report muscle loss when taking it (20).

    References:

    https://www.storeboard.com/HarryNencini-7084107

  6. Asking questions are genuinely fastidious thing if you are not understanding
    anything totally, however this paragraph provides good understanding yet.

  7. Site - Si表示:

    Hey folks,

    I’ve been diving into the world of online casinos lately, and I’ve gotta say — it’s way more exciting than I expected. At first, I was a bit wary. I mean, how do you even believe in an online platform with your money, right? But after doing a ton of research (and trying out a few sketchy sites so you can avoid that mess), I figured out a few things that set apart a trustworthy casino from a risky mess. First off, if you’re new to all this, here’s the golden rule: **regulation is key**. If a casino doesn’t have a proper legal status (like from the MGA or the UK Gambling Commission), just run. No bonus is worth the gamble of never seeing your funds again. Also — and I know no one wants to — read the T&Cs. That’s the only way to know what kind of playthrough limits they’ve slapped onto those so-called “juicy” bonuses.

    Now, let me share a site I’ve been hooked on these last few weeks. It’s been a total win. The interface? Super easy to navigate. Payouts? Quick — like 24 hours quick. And the game selection? *Wild*. Slots, live dealers, blackjack, even some weird niche games I hadn’t tried before. Check it out here: http://jicc.kr/bbs/board.php?bo_table=hosung3&wr_id=325593 What really stood out was the support team. I had a tiny issue with a bonus not working, and they got back to me in like instantly. Compare that to other sites where you’re just ghosted by support — yeah, no thanks.

    Also, if you’re into bonuses (and who isn’t?), this place offers some juicy ones. But here’s the trick: don’t just grab every shiny offer. It’s smarter to get fair terms than a huge bonus you’ll never be able to withdraw. I’m not saying you should go and blow your whole paycheck — please don’t. But if you’ve got a little extra cash and you’re looking for a bit of online excitement, online casinos can totally deliver. Just stay sharp, set a budget, and don’t treat it like a side hustle. It’s for fun, not for a paycheck. Anyway, just wanted to drop my experience here in case anyone’s curious or trying to find a trustworthy place to play. If you’ve got your own stories or even some casino nightmares, I’m all ears — love talking shop about this stuff.

    Good luck out there, and spin smart, win big ??

  8. Nonetheless, we have discovered testosterone to
    be essentially the most cardiovascular-friendly steroid.
    Thus, cholesterol levels is not going to expertise dramatic elevations compared
    to a Dianabol-only cycle. In terms of side effects, testosterone suppression might be extra dramatic with this stack in comparability with a Dianabol-only cycle.
    Thus, diligent post-cycle remedy (PCT) is necessary to stop testosterone deficiency
    syndrome (TDS). We will examine essentially the most prevalent Dianabol stacks utilized by bodybuilders from the Golden Period to the current day.

    We will present cycle data on the appropriate dosages and durations of use.

    Very little Oxandrolone is produced for human medical use these days, so there’s
    hardly any provide of pharma-grade products.
    That means it won’t be low-cost if yow will discover
    some (and be sure it’s legitimate and genuine).

    Ladies who’re comfy with higher doses of Anavar and who don’t endure virilization results can consider adding another 5-10mg to the
    Anavar dose suggestion above.
    Some of the frequent unwanted aspect effects embrace pimples, hair loss, and increased body hair development.
    It is also essential to observe proper post-cycle therapy (PCT)
    to help your physique recuperate from the cycle.
    Being the primary, naturally occurring male hormone, testosterone is
    probably considered one of the mostly used anabolic steroids among bodybuilders.

    This was an excessive cycle period, with a normal cycle
    size of 6–8 weeks for men. From this examine, we are in a position to conclude
    that natural testosterone production is likely to
    stay fairly excessive if a reasonable dose or cycle
    is performed. Are you able to delve into the world
    of performance-enhancing steroids? Whether Or Not you’re
    a seasoned bodybuilder or somebody exploring the
    chances, the choice between dianabol and Anavar may be perplexing.
    Both of those in style anabolic steroids have their very own set of unique advantages and
    considerations.
    An essential factor to contemplate when planning your Anavar stack is the significant advantage of its lack
    of water retention because it doesn’t convert to estrogen. You can use this by stacking
    it with other compounds that don’t aromatize, like Trenbolone and Masteron. Such a stack can effectively have
    you ever not having to assume about fluid retention at all
    except you resolve to take the next dose of testosterone
    within the stack. Stacking Anavar will almost solely be for chopping and recomposition cycles for male
    customers.
    The annoying factor is that DHT just appears to be a
    hormone which has a much simpler time eradicating your hair.
    You must always keep in mind although that it is not the DHT
    alone that causes hair-loss, it is a complex sequence of enzymes
    and hormones that are usually triggered by a excessive Androgenic environment.
    While Dianabol is an unlawful compound, D-BAL has been fomulated with pure elements and don’t break the legislation. A combination of proteins and Amino Acids
    together with PeakATP is certain to help you barely in the muscle gaining
    endeavor. It should be noted that this isn’t a particularly protected, effective or sustainable
    practice in terms of longer-term AAS utilization, however
    it could be beneficial in certain circumstances.
    There is a common notion that women don’t require post-cycle remedy.
    Nevertheless, in practice, we discover ladies expertise a number of signs of
    clinically low testosterone levels following anabolic steroid
    use. Anavar’s advantages aren’t overly highly effective,
    at least compared to different anabolic steroids; therefore,
    the unwanted effects are more tolerable for many users.

    However, it’s not merely power and endurance athletes that will
    profit from Anavar, with some sprinters, swimmers,
    and boxers also using Anavar to realize a competitive edge.
    Masculinization is still attainable if doses larger than 10
    mg a day are utilized. Studies have reported women experiencing virilization effects when receiving high doses of zero.125 mg per kg (13) continuously for
    a 12 months. Anavar is a by-product of dihydrotestosterone; thus, there is no conversion to
    DHT via the 5-alpha reductase enzyme. Consequently, Anavar
    has mild androgenic properties and unwanted effects.
    We have had sufferers report important energy results on Anavar, even when consuming low calories.
    This can be why powerlifters typically administer Anavar prior to a contest for optimum energy without
    important weight acquire.
    It also has low androgenic activity so it’s not as prone to trigger unwanted effects like
    hair loss or zits. When it involves sheer strength, Dianabol emerges because the undisputed champion. This potent anabolic steroid works wonders
    by enhancing protein synthesis and growing red blood cell depend, facilitating better
    oxygen supply to the muscular tissues.
    When you take it, you will boost your body’s capability to produce pink blood cells, ensuring that your pink blood cell rely is maintained
    and facial hair progress is averted. That’s as a result of elevated ranges of testosterone coursing
    via your body while you are coaching will present you with
    more calcium inside your muscle cells. This will improve
    the force of your muscular contractions, leading to 30 % more power.
    If you’re a newbie, I’ll explain every thing you need
    to know, so as to pack on muscle with out risking your well being with unlawful steroids,
    but choosing authorized alternatives as an alternative.

    Yes, Dianabol is on the market in oral type and is usually taken as a tablet.

    Dianabol had an anabolic rating that was larger than that of testosterone, and its androgenic effects had
    been less pronounced. We incessantly observe Deca Durabolin eliciting impotence throughout a cycle, which might have an unlucky effect on the sexual health of male users.

    This is the end result of Deca Durabolin’s considerably rising prolactin ranges.
    We prescribe cabergoline to sufferers to handle this imbalance, inhibiting the production of prolactin and sustaining libido.

    References:

    Is Creatine A Steroid (http://Www.Iconfinder.Com)

  9. Williamwhogs表示:

    olympe casino en ligne: olympe casino – olympe casino cresus

  10. Mazrder表示:

    Мы предлагаем дипломы любых профессий по выгодным тарифам. Стараемся поддерживать для клиентов адекватную политику тарифов. Для нас очень важно, чтобы документы были доступными для большого количества граждан.
    Приобретение документа, который подтверждает окончание ВУЗа, – это выгодное решение. Купить диплом университета: nsk-diplom.com/gde-kupit-diplom-ob-okonchanii-kolledzha/

  11. 1win_qqKn表示:

    1вин сайт официальный http://1win7020.ru .

  12. AlbertShund表示:

    https://olympecasino.pro/# olympe casino en ligne

  13. маркетплейс игровых аккаунтов https://marketplace-akkauntov-top.ru

  14. 1win_xqKn表示:

    1win официальный сайт вход http://1win7020.ru .

  15. Gregoryron表示:

    olympe casino cresus: olympe casino – olympe casino cresus

  16. Ronaldbet表示:

    olympe casino olympe casino en ligne

  17. AlbertShund表示:

    https://olympecasino.pro/# casino olympe

  18. Good day I am so happy I found your site, I really found you
    by mistake, while I was browsing on Google for something else, Anyhow I am
    here now and would just like to say many thanks for a incredible post and a all round enjoyable blog (I also love the theme/design), I don’t have time to go through it all at the minute but
    I have bookmarked it and also added in your RSS feeds, so when I have time I will
    be back to read a great deal more, Please do keep up the awesome work.

  19. Mazrnas表示:

    Мы изготавливаем дипломы любых профессий по невысоким ценам. Всегда стараемся поддерживать для клиентов адекватную ценовую политику. Для нас важно, чтобы дипломы были доступны для большинства наших граждан.
    Заказ диплома, который подтверждает обучение в ВУЗе, – это разумное решение. Заказать диплом ВУЗа: 1magistr.ru/kupit-diplom-ekaterinburg-2/

  20. vai-de bet表示:

    Best Online Casinos for Roulette Players
    Top Online Casinos for Roulette Enthusiasts
    In the expansive universe of virtual gaming, few options command as much attention as the
    spinning wheel and the anticipation of the ball’s descent.

    This article explores premier destinations that cater specifically to individuals who appreciate the thrill of this classic fixture.

    What sets these platforms apart? It’s the combination of user
    experience, variety of formats, and promotional offerings designed for optimal engagement.

    Statistical analysis reveals that certain sites consistently outperform others in terms of payout rates and user satisfaction. With a meticulous approach to selection, we highlight venues that boast high return-to-player (RTP) percentages,
    ensuring that every spin is enriched by the potential for lucrative outcomes.
    Bonuses and incentives also play a significant role, providing extra motivation to explore different versions
    of this timeless pursuit.
    Accessibility remains a key factor in modern gaming. The recommended sites feature seamless interfaces compatible with various devices, allowing
    enthusiasts to enjoy their favorite activities at
    home or on the go. Furthermore, innovative features such as live dealer experiences and interactive elements
    enhance immersion, making each session uniquely exciting.
    This guide aims to offer insightful recommendations, ensuring that every enthusiast can find their ideal gaming destination with ease.

    Top Features to Look for in Online Casinos for Roulette
    When selecting a platform for roulette experiences, focus on several
    key attributes that enhance gameplay and security. First, check for licensing and regulatory approval from recognized authorities like
    the UK Gambling Commission or the Malta Gaming Authority, which
    ensure fair practices.
    Payment methods play a significant role; options should include a variety of reliable methods such as credit cards,
    e-wallets, and cryptocurrencies. Fast transactions, minimal fees, and robust security
    measures should be standard features to protect your financial information.
    The software developers behind the roulette games are
    crucial. Look for titles provided by reputable companies like NetEnt, Microgaming,
    or Evolution Gaming, known for their high-quality graphics, smooth
    gameplay, and innovative features.
    Live dealer options offer an immersive experience through
    real-time interaction with dealers. A platform that provides multiple live tables with varying betting limits caters to different player preferences.

    Bonuses and promotions can significantly impact your playing experience.
    Analyze the terms and conditions associated with welcome bonuses,
    free spins, and loyalty programs to ensure you gain maximum value without excessive wagering
    requirements.
    Customer support is another factor; responsive and knowledgeable
    service available through various channels (like live chat, email,
    and phone) can resolve issues swiftly, contributing to a seamless experience.

    Lastly, the range of inclusive gameplay options is paramount,
    including variations like European, American, and French roulette, as well
    as immersive versions that introduce unique twists
    to traditional formats. A diverse game library keeps the experience fresh and engaging.

    How to Choose the Right Variants for Your Playing Style
    Selecting an appropriate variant can significantly impact your experience and outcomes.
    Evaluate the key characteristics of different versions to identify which suits your
    preferred tactics and risk appetite.
    One major aspect to consider is the layout. European versions feature
    a single zero, enhancing the odds in favor of the player compared to American variants with
    both single and double zeros. This distinction can affect your betting strategy.

    If you prefer lower house edges, focus on options that
    reflect this setup.
    Next, explore the betting options provided by various editions.
    Some variants offer unique betting formations, enabling you
    to place minimum and maximum stakes. If you enjoy
    taking calculated risks, look for alternatives that allow for a range of betting strategies,
    like inside and outside bets.
    Consider speed of play as well. Live dealer formats offer interactive experiences, ideal for those who like social engagement during sessions.
    On the other hand, electronic formats may provide faster rounds for individuals who prefer quick
    decision-making.
    A third element to explore is the presence of special features
    or unique rules. Some variants incorporate additional side bets or bonuses.

    If you appreciate complexity, seek out alternatives that introduce unique mechanics to enhance the gameplay experience.

    Lastly, familiarity can greatly enhance your comfort.
    If you’re new or prefer a straightforward experience, opt for traditional versions.

    As your skills develop, you might want to branch out into those with more intricate rules or innovative features.
    Always keep your long-term enjoyment and understanding in mind when choosing.

    Here is my webpage :: vai-de bet

  21. read here表示:

    Wow, awesome blog layout! How long have you been blogging for?
    you make blogging look easy. The overall look of your website is great, as well
    as the content!

  22. Williamwhogs表示:

    olympe: olympe casino cresus – casino olympe

  23. I know this if off topic but I’m looking into starting
    my own blog and was wondering what all is required to get set up?

    I’m assuming having a blog like yours would cost a pretty penny?
    I’m not very web smart so I’m not 100% certain. Any recommendations or advice would be greatly appreciated.
    Thank you

  24. Gregoryron表示:

    olympe casino: olympe casino avis – olympe casino cresus

  25. Mazrsyv表示:

    Мы изготавливаем дипломы любой профессии по приятным тарифам. Стараемся поддерживать для заказчиков адекватную ценовую политику. Для нас очень важно, чтобы документы были доступными для подавляющей массы граждан.
    Покупка документа, подтверждающего окончание университета, – это грамотное решение. Приобрести диплом университета: diplom-insti.ru/diplom-o-srednem-professionalnom-obrazovanii-kupit-3/

發佈回覆給「vai-de bet」的留言 取消回覆

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