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,676,148 Responses

  1. Williamwhogs表示:

    olympe casino cresus: olympe casino avis – olympe casino avis

  2. fox sex video表示:

    Megan Fox’s sex tape video clip is currently offered.
    Warm!

  3. Site - Si表示:

    Hey everyone,

    I’ve been diving into the world of internet gambling lately, and I’ve gotta say — it’s pretty damn addictive. At first, I was a bit wary. I mean, how do you even believe in an online platform with your cash, right? But after testing the waters (and trying out a few dodgy sites so you can avoid that mess), I figured out a few things that separate a legit casino from a complete fraud. 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 regulatory certificate (like from the Malta Gaming Authority or the UK Gambling Commission), just close that tab. No bonus is worth the trouble 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 “generous” 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? Fast as hell. And the game selection? *Insane*. Slots, live dealers, blackjack, even some oddball options I hadn’t tried before. Check it out here: http://www.cycle2yorktown.com/guestbook What really stood out was the customer service. I had a tiny issue with a bonus not working, and they got back to me in like no time. Compare that to other sites where you’re just shouting into the void — yeah, not worth it.

    Also, if you’re into bonuses (and who isn’t?), this place offers some juicy ones. But here’s the trick: don’t just chase bonuses. It’s smarter to get clear terms than a huge bonus you’ll never be able to withdraw. I’m not saying you should go and drop your rent money — please don’t. But if you’ve got a little extra fun budget and you’re looking for a chill way to spend an evening, online casinos can totally deliver. Just play smart, control your bankroll, 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 decent place to play. If you’ve got your own recommendations or even some horror tales, I’m all ears — love talking shop about this stuff.

    Good luck out there, and may the odds be ever in your favor ??

  4. 1с какие есть программы http://programmy-1s15.ru .

  5. 1с какие есть программы http://programmy-1s15.ru/ .

  6. Louisveige表示:

    This guide explores the core SEO strategies needed to increase visibility for your gambling app, attract more users, and improve your rankings TELEGRAM @SEO_ANOMALY – SEO BACKLINKS, BLACK-LINKS, TRAFFIC BOOST, LINK INDEXING

  7. проведение оценки профессиональных рисков в Москве ocenka-profriskov495.ru .

  8. Selecting Online Casinos with High Engagement Scores
    Selecting an Online Casino with High Engagement Scores
    Engagement in virtual gaming environments serves as a crucial
    indicator of user satisfaction. By assessing interaction levels, players can identify venues that not
    only prioritize entertainment but also foster community.
    This aspect can dramatically influence one’s overall experience and loyalty to a particular
    site.
    In evaluating alternatives, it’s wise to investigate features like real-time chat options, community events, and
    reward systems. Platforms that promote social interactions often see higher retention rates due to enhanced player experiences.
    Data reveals that venues incorporating these elements report up to a 30% increase in active user accounts.

    Moreover, look for analytics that detail time spent on site
    and returning visitor statistics. Engagement
    metrics often correlate with the availability of diverse gaming options and user-friendly interfaces.

    A study highlighted that players are 40% more likely to return to environments where
    they feel engaged and valued through tailored experiences.

    Evaluating Casino Features That Drive User Interaction
    Understanding what encourages players to engage consistently is key for
    operators and developers. Several specific features significantly boost user participation and satisfaction levels.

    Game Variety: A diverse library of games is fundamental.
    Including various genres such as slots, table games, and live dealer options caters to distinct
    preferences. Regularly updating the selection with new titles
    keeps the experience fresh and exciting.
    Interactive Elements: Incorporating features like chats or
    live tournaments enhances player interaction. Social elements create a sense of community, allowing users to connect with
    others and share experiences, making the gaming process more enjoyable.

    User-Friendly Interface: Navigation must be intuitive, enabling players
    to find their favorite games swiftly. A well-organized layout reduces frustration, enhancing overall satisfaction. Mobile compatibility plays a
    crucial role, as many users prefer gaming on the go.

    Bonuses and Promotions: Attractive incentives significantly influence user
    retention. Clear and achievable bonus structures, loyalty programs, and promotional events invite players to return regularly.
    Transparency about terms is vital to maintain trust.

    Customer Support: Providing robust and responsive
    support options fosters a positive relationship
    between players and the platform. Multiple channels, including live chat, email, and FAQs,
    ensure that users can resolve any issues promptly.

    Security Measures: Ensuring player data protection builds trust.
    Implementing advanced security protocols reassures users that
    their information is safe, encouraging them to engage more fully.

    By focusing on these specific elements, operators can create
    environments that not only attract players but
    also encourage ongoing interaction, enhancing their overall
    experience.
    Understanding the Importance of Customer Support and Community Engagement
    Quality service is a pivotal aspect that significantly shapes player experiences.
    Access to prompt and reliable customer assistance can transform potential challenges into manageable situations.
    A casino that provides multiple support channels–such as live chat, email, and telephone–enables swift resolution of issues, effectively enhancing
    user satisfaction. Players appreciate platforms that offer 24/7 support,
    helping to alleviate anxieties regarding account management or
    game related inquiries.
    In addition to robust customer service, building a sense of community plays a crucial role in retaining players.
    Engaging forums and social media platforms can serve
    as spaces for players to connect, share experiences, and discuss strategies.
    By fostering interactions, a venue cultivates loyalty and a sense of belonging
    among its user base. Active community management–such as hosting tournaments or polls–can provide valuable
    feedback to operators and create a more invested audience.

    Moreover, integrating feedback mechanisms is paramount.

    Platforms that regularly solicit player opinions through surveys or
    suggestion boxes not only show that they value user input but also pave the way for continual improvement.
    This transparency fosters trust and encourages long-term
    engagement, as players feel their voices contribute to a
    better overall experience.
    In conclusion, prioritizing customer assistance and community interaction not only enhances player satisfaction but also promotes retention in a competitive environment.

    Establishing these foundations is fundamental for any operator aiming to
    thrive and create a positive atmosphere for their users.

    Here is my homepage :: betonred kasyno

  9. VictorVal表示:

    olympe casino: olympe casino – olympe

  10. JosephCrimi表示:

    This article will tell you in more detail how to register with 1xBet with a promotional code https://www.guidasposi.it/com/pgs/?promo_code_51.html

  11. Warm Arab shemale likes anal sex, prepare yourself for the adventure!

    #AnalLove

  12. Sabina表示:

    This is as a outcome of steroids are highly effective drugs that
    can trigger serious side effects if they don’t appear to be used accurately.
    Anavar may also suppress endogenous testosterone,
    causing a state of hypogonadism post-cycle. This usually recovers in a matter of weeks post-cycle; nonetheless, abuse of Anavar might
    result in long-term testosterone deficiency.
    Those like Lee Priest or outspoken bodybuilder ‘Aarron Lambo’ who are not afraid to talk
    up and reveal some of the darker secrets of the bodybuilding world.
    In this article I’m going to outline some
    unfavorable reactions you may expertise on Anavar,
    so you can also make an informed decision on whether the pros outweigh the cons
    when taking this anabolic steroid. Some folks say
    they don’t notice a lot on anavar, which I put right down to a too-low dose.

    At All Times comply with your doctor’s directions on when and the means
    to take Anavar. Most people begin with a lower dose and progressively improve it to see how their body reacts.
    Regardless of the rationale for taking Anavar, observe the recommended dosage
    and do not exceed it, as this can provoke severe well being issues.
    Throughout this time, the person takes Anavar day by day in a particular dosage – more on this instantly under.
    Some folks additionally use different supplements or
    drugs through the cycle to boost the consequences or to assist with recovery afterward.
    However, cycling with out correct medical steering could be harmful
    and result in dangerous side effects.
    Not Like different anabolic steroids with significant androgenic results, Anavar’s structural
    modification enhances its selectivity for anabolic pathways while minimizing undesirable androgenic stimulation. Nevertheless, clenbuterol isn’t an anabolic steroid; therefore, we don’t see it
    affect pure testosterone ranges to any important degree.
    However, we know of bodybuilders which have retained virtually all of their outcomes on Anavar when they
    proceed regular weight coaching. Such profitable muscle retention may be attributed to
    Anavar not aggressively shutting down endogenous testosterone manufacturing.
    Therefore, taking Anavar can increase the risk of arteriosclerosis and can almost
    actually raise blood stress in all customers.
    If excessive doses are taken, cardiovascular side effects can become severe, resulting in hypertension, heart illness, or stroke.

    While each may help help your fat burning and weight loss journey, they do it in completely alternative
    ways. That’s why, we can’t say which one is better, you will want to seek out out for yourself, based mostly
    on your private response and response to every compound.
    Anavar is a steroid and Clenbuterol isn’t (it is a stimulant), working in different methods.
    Additionally, when you cease using Anavar, you might have withdrawal symptoms that can final from
    a few days to two weeks. It’s a good suggestion to speak to a doctor or a sports activities official if you’re worried about steroid use and drug testing.
    But keep in mind, some athletes would possibly use “masking” drugs to
    eliminate steroids, which is not only in opposition to the rules but also actually dangerous on your well being.

    If a girl unknowingly takes Dianabol, virilization unwanted
    effects are very likely. We have found Anavar to be a potent muscle-builder; nonetheless, it’s not going to remodel
    the typical lady into a 200-pound man (like some would possibly believe).
    Gynectrol has been specifically formulated to naturally melt away unwanted chest fat.
    In conclusion, while there are other ways to get Anavar, it
    is very important be cautious and do your
    research earlier than making a purchase. Sure,
    in case your doctor believes Anavar is medically essential
    for you, they can prescribe it to you. However, they
    might refer you to a specialist if they aren’t comfortable prescribing
    it themselves.
    Still, we should always do not overlook that even a 4-week cycle of Anavar can produce outcomes, which will hold prices down considerably.
    Some suppliers around will promote steroids labeled as
    Oxandrolone, which include a very different
    (and cheaper) AAS like Dianabol. Anavar have to be sourced fastidiously
    to make sure you get what you want – correctly dosed and high-purity Oxandrolone (preferably pharmaceutical-grade).

    Availability and ease of entry, authorized conditions, and pricing of Oxandrolone will differ throughout totally different
    elements of the world. The dosing of Clen at all times needs to be tapered as a lot as keep away from outcomes plateauing as
    your physique adjusts.
    A 2004 study involving men aged years old, who maintained a 20mg daily Anavar dosage, showed a
    noticeable reduction in body fat over a 12-week period.
    And 12 weeks after the check topics stopped utilizing the drug,
    they retained 83% of their reductions in complete, trunk, and extremity fat (3).
    One Other examine revealed that males aged years old
    also skilled a major amount of Anavar weight loss (4).
    Anavar may cause folks to burn more fat and construct lean muscle, increasing strength.
    The anabolic effects of this steroid are stronger than its
    androgenic effects.
    It’s popular amongst bodybuilders because anavar’s thought of a
    mild compound. Though there are a number of unwanted facet effects, as a outcome of it’s not overly highly effective
    or toxic, most of these side effects can usually be avoided.
    Not Like another popular dihydrotestosterone derived anabolic
    steroid in Anadrol, Anavar is what we’d name a rather aspect impact friendly anabolic steroid.

    Facet results are actually potential, however for the healthy adult they are often minimized.
    In truth, with responsible use, many will discover
    they expertise no unfavorable effects at
    all.
    Anavar (Var, Var 15) was first developed in 1962 by pharmaceutical giants
    G.D. Searle & Co (Now Pfizer) and was sold within the
    Usa and the Netherlands under the Anavar commerce name.
    It is a DHT derived anabolic steroid, much like Masteron and
    Winstrol. It is an orally lively 17-alpha-alkylated compound, giving it the ability
    to survive the “first pass” of liver metabolism and permitting it to be ingested successfully.
    It is a versatile androgen and can be utilized in both chopping and bulking stacks/phases.
    If you’re shopping for anavar for its capacity to burn fats and you’re
    brief on cash, a extra cost-efficient choice could additionally be clenbuterol.

    Nonetheless, as a outcome of Anabolic Steroids Control
    Act of 1990, Anavar turned unlawful to buy and not using a medical cause.
    Thus, common prescriptions for bodybuilders and athletes were
    not issued. Testosterone levels usually get well one to 4 months after Anavar cycle cessation. An effective
    PCT protocol can speed up the restoration of endogenous testosterone.

    References:

    did schwarzenegger use steroids (Sabina)

  13. sediaqq表示:

    Hello just wanted to give you a quick heads up. The words in your post seem to be
    running off the screen in Ie. I’m not sure if this is a formatting issue or something to do with web
    browser compatibility but I thought I’d post to let you
    know. The design and style look great though! Hope you get the
    issue fixed soon. Kudos

  14. 1win_whKn表示:

    1win скачать kg https://1win7020.ru/ .

  15. 1с бухгалтерия сопровождение программного http://www.programmy-1s15.ru/ .

  16. оценка уровня профессионального риска (Москва) оценка уровня профессионального риска (Москва) .

  17. проведение оценки профессиональных рисков в Москве ocenka-profriskov495.ru .

  18. оценка уровня профессионального риска (Москва) оценка уровня профессионального риска (Москва) .

  19. mostbet_msea表示:

    мостбет войти http://mostbet7004.ru .

  20. Mazrjvj表示:

    Мы можем предложить дипломы любой профессии по невысоким ценам. Всегда стараемся поддерживать для заказчиков адекватную политику цен. Для нас важно, чтобы дипломы были доступными для подавляющей массы наших граждан.
    Заказ диплома, подтверждающего обучение в ВУЗе, – это выгодное решение. Купить диплом университета: kupit-diplomyz24.com/meditsinskij-kolledzh-kupit-diplom-5/

  21. Williamwhogs表示:

    casino olympe: olympe casino cresus – casino olympe

  22. 1с бухгалтерия сопровождение программного programmy-1s15.ru .

發佈留言

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