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,957 Responses

  1. I truly appreciate the effort behind this amazing website. Its a wonderful resource that has made my life so much easier. Thank you for creating something so impactful.

  2. Uazrzwr表示:

    Приветствую!
    Для некоторых людей, купить диплом о высшем образовании – это необходимость, уникальный шанс получить достойную работу. Однако для кого-то – это разумное желание не терять огромное количество времени на учебу в институте. С какой бы целью вам это не потребовалось, наша компания готова помочь вам. Максимально быстро, качественно и выгодно изготовим диплом любого года выпуска на подлинных бланках со всеми подписями и печатями.
    Ключевая причина, почему многие люди прибегают к покупке документа, – желание занять хорошую должность. Предположим, навыки и опыт дают возможность человеку устроиться на привлекательную работу, но подтверждения квалификации нет. При условии, что работодателю важно наличие “корочки”, риск потерять место работы очень высокий.
    Заказать документ ВУЗа вы имеете возможность в нашей компании в столице. Мы оказываем услуги по изготовлению и продаже документов об окончании любых ВУЗов РФ. Вы сможете получить необходимый диплом по любой специальности, включая документы старого образца. Гарантируем, что при проверке документов работодателем, каких-либо подозрений не возникнет.
    Ситуаций, которые вынуждают заказать диплом о среднем образовании достаточно. Кому-то прямо сейчас нужна работа, а значит, необходимо произвести хорошее впечатление на руководителя в процессе собеседования. Другие мечтают устроиться в серьезную компанию, для того, чтобы повысить свой статус и в дальнейшем начать свой бизнес. Чтобы не терять впустую годы жизни, а сразу начинать успешную карьеру, применяя врожденные таланты и приобретенные навыки, можно приобрести диплом прямо в онлайне. Вы станете полезным для социума, обретете финансовую стабильность очень быстро и просто- купить диплом о высшем образовании

  3. WebSite - i8表示:

    Reasons Why Online Casinos Are Booming
    There are many reasons why online casinos have gained massive traction. One of the biggest advantages is accessibility. Unlike physical casinos that have operating hours, internet-based casinos never close, ensuring round-the-clock entertainment.

    One of the strongest attractions is the enormous range of gaming options available. While land-based venues have space constraints, online casinos provide an endless assortment of games. From classic fruit machines to cutting-edge video slots with immersive themes, the choices are practically limitless. For exclusive deals and insights into the best casinos, check out our social media page! – http://bcbhartia.gridlearn.com/2024/12/26/1win-casino-y-casa-de-apuestas-ofrece-diversion-y-emocion-en-cada-jugada/

    How Online Casinos Keep Players Engaged

    One of the biggest draws of online casinos is the generous promotions and bonuses. Many platforms offer newcomers fantastic welcome packages, boosting their bankroll instantly. The more you play, the more rewards you unlock, from cashback to personalized bonuses. Not all casino games are about luck—some demand strategic thinking and expertise. In games like poker, knowledge and tactics can give players a significant edge over less experienced opponents. If you prefer a fast-paced, unpredictable experience, slots and roulette provide thrilling, luck-based gameplay.How to Gamble Responsibly Online

    As exciting as online gambling can be, it’s essential to practice responsible gaming. Smart bankroll management and self-control help players maintain a healthy approach to gambling. Reputable platforms also promote responsible gaming by offering tools like deposit limits, self-exclusion, and links to gambling support organizations. Are you an online casino enthusiast? What’s your go-to game? Drop your opinions and stories in the discussion thread!

  4. Console表示:

    Hi there mates, how is the whole thing, and what you would like
    to say about this post, in my view its really amazing in support of me.

    Feel free to visit my webpage … Console

  5. VictorTuM表示:

    All links are in the description! (that mean – here) Valve want us to use Steam Guard Mobile Authenticator at all cost https://sdasteam.com/

  6. kmyprgqdd表示:

    Desarrollador: GameDistribution ESTE JUEGO ES MUY DIVERTIDO PARA JUGARLO CADA VEZ QUE ME LA GANAAAAA Entretenimiento Ratón: chuta el balón y defiende la portería Friv 10, Friv 26, Friv 99, Friv 215, Friv 251, Friv 899, Friv 1015, Friv 8000, Friv 10100, Friv group, England Premier League England Premier League football.. Haga clic con el botón izquierdo para detener los indicadores y atrapar la pelota. England Premier League football.. Penalty Shooters Use Left Mouse button to Stop the indicators and catch the ball, football.. football.. The game offers numerous options to adjust difficulty levels, making it suitable for players of all skill levels. Whether you’re a beginner or an experienced player, there’s always room to improve and challenge yourself further. Penalty Shooters Ahora, puedes jugar Penalty Shootout: Multi League en PC con GameLoop sin problemas.
    http://musstabpaython1982.tearosediner.net/mas
    The Draw No Bet market is popular for Primera Division matches, with the football betting sites offering Racing Club at 1.50 and Boca Juniors are priced at 2.50 for the win. bplay.bet.ar | Todos Los Derechos Reservados © 2024 – bplay La popularidad del juego ha crecido rápidamente entre los apostadores mexicanos. Este dinámico minijuego combina fútbol y azar en una experiencia interactiva que puedes disfrutar en varios casinos en línea. Aquí te mostramos dónde puedes hacer tu penalty shootout bet de forma segura y entretenida: Веt365 tіеnе unа арlісасіón móvіl раrа uѕuаrіοѕ dе іОЅ у Αndrοіd. Unа vеz quе іnѕtаlеѕ lа арр еn tuѕ dіѕрοѕіtіvοѕ, рοdráѕ еmреzаr а јugаr а Ρеnаltу Ѕhοοt Оut. Lа арlісасіón еѕtá tοtаlmеntе οрtіmіzаdа раrа ѕu uѕο móvіl, рοr lο quе tu tеléfοnο у tаblеtа funсіοnаrán а lа реrfессіón mіеntrаѕ јuеgаѕ. Υ lο quе еѕ máѕ іmрοrtаntе, lа арlісасіón ѕе hа dеѕаrrοllаdο сοn unа іntеrfаz іntuіtіvа у unа nаvеgасіón fáсіl dе uѕаr.

  7. тревожная кнопка стоимость http://www.trevros.ru .

  8. Thomaspneus表示:

    WEB PAFI TERINTEGRASI: Fungsi Penting Farmasi dalam Era Digital

    Profil Singkat PAFI
    Pasca kemerdekaan RI, para Ahli Farmasi memberikan andil dalam kemajuan kesehatan bangsa. Berdirinya Persatuan Ahli Farmasi Indonesia (PAFI) menjadi langkah strategis sebagai asosiasi di bidang farmasi. Berdasarkan Pancasila, PAFI bersumpah untuk:

    • Mengembangkan derajat kesehatan masyarakat

    • Mengembangkan kefarmasian nasional

    • Memperbaiki kualitas hidup anggota

    Sistem Digital PAFI: Solusi Digital untuk Dunia Farmasi Digital

    Menghadapi tantangan era digital, PAFI menghadirkan WEB PAFI Terintegrasi – terobosan teknologi yang menunjang praktik farmasi profesional melalui:

    ? Update Terbaru – Akses regulasi kesehatan, temuan terbaru, dan prospek pekerjaan

    ? Pengembangan Kompetensi – Program pembelajaran jarak jauh

    ? Jejaring Profesional – Wadah kolaborasi se-Indonesia

    Inovasi teknologi ini meningkatkan peran PAFI dalam meningkatkan kesehatan nasional melalui penerapan inovasi digital.

    Tantangan Kefarmasian Era Digital

    Hadirnya WEB PAFI Terintegrasi merupakan tanda perubahan sistem dalam dunia kefarmasian. Dengan selalu menyempurnakan kapabilitas sistem, PAFI bertekad untuk:

    • Mendorong terobosan dalam farmasi

    • Memperkuat kualitas profesi

    • Memperluas pelayanan kesehatan publik

    Penutup

    PAFI berkat sistem terpadu ini terus menjadi pionir dalam memadukan inovasi digital dengan praktik farmasi profesional. Program ini tidak hanya meningkatkan fungsi ahli farmasi, tetapi juga memberikan sumbangsih konkret bagi kemajuan kesehatan bangsa di masa modern.

  9. FrankGlora表示:

    UsaIndiaPharm: top 10 online pharmacy in india – USA India Pharm

  10. Hi great blog! Does running a blog similar to this require a massive amount work?

    I have very little knowledge of coding however I was hoping to start my own blog soon. Anyways, if you have any ideas or tips for new blog owners please share.
    I know this is off subject however I just wanted
    to ask. Thanks a lot!

  11. mostbet_gcPt表示:

    mostbet промокод mostbet5002.ru .

  12. ThomasEstag表示:

    Телефон: +7(495)640-11-87 E-mail: edmolift@mls.ltd.
    Стол устойчивый, подъёмный механизм обеспечивает плавное движение груза, мобильный. В компании «Адванта-М Сибирь» в Красноярске гидравлический стол вы купите по выгодной цене первого импортера! Оформляйте заявку онлайн, и мы зарезервируем товар на складе!
    Арт. 700058.
    Характеристики.
    Грузоподъёмность: 250 кг. Высота подъёма: 890 мм. Размер стола: 815х500 мм. Колеса: 125х40 мм. Гарантия: 15 месяцев.
    TF75 NOBLELIFT Подъемный стол гидравлический.

  13. Trefdgd表示:

    Купить диплом института. Покупка документа о высшем образовании через надежную фирму дарит немало достоинств для покупателя. Это решение помогает сэкономить как личное время, так и значительные финансовые средства. neejobs.com/employer/eonline-diploma

  14. Ethereum Olux表示:

    Thanks for some other fantastic article. Where else may just anyone get
    that type of info in such a perfect means of writing? I’ve a presentation subsequent week, and I am at the look for such information.

  15. 1win_foPt表示:

    1 win официальный сайт вход 1 win официальный сайт вход .

  16. It’s a no go for me, I do not intend to have sex with my sibling.

  17. DavidSooni表示:

    UsaIndiaPharm online shopping pharmacy india USA India Pharm

  18. Waltonnix表示:

    Online medicine home delivery: UsaIndiaPharm – USA India Pharm

  19. FrankGlora表示:

    USA India Pharm: UsaIndiaPharm – UsaIndiaPharm

  20. fkgropylb表示:

    Para jugar Penalty Shoot-Out en un casino en línea, primero elige un casino licenciado y regulado para garantizar tu seguridad. Regístrate y deposita fondos utilizando tu método de pago preferido. Una vez que tu cuenta esté financiada, encuentra el juego Penalty Shoot-Out en la biblioteca del casino. Ajusta tu apuesta, sigue las instrucciones del juego para jugar y apunta a marcar goles. Puedes recoger tus ganancias o seguir jugando, pero juega estratégicamente para evitar pérdidas. Cuando estés listo, retira tus ganancias a través de la sección de caja. Recuerda siempre jugar con responsabilidad y busca ayuda si es necesario. JUEGO CRASH INSPIRADO EN EL FÚTBOL Obtén un multiplicador total de hasta x25000 Conéctate con otros fanáticos y entusiastas de Penalty Shoot-Out uniéndote a nuestro grupo de Telegram dedicado. Comparte consejos, estrategias y experiencias, y mantente actualizado sobre las últimas noticias y promociones relacionadas con el juego. Ya sea que busques consejos sobre el juego o simplemente quieras interactuar con personas afines, nuestro grupo de Telegram ofrece una comunidad vibrante para todos los entusiastas de Penalty Shoot-Out. No te pierdas la oportunidad de
    https://mediasuitedata.clariah.nl/user/adcomutact1983
    Site Oficial No Brasil: Cadastro, Jogos E Bônus Content O Suporte Ao Cliente Está Disponível No Brasil? Como Jogar Not Any Pin-up” “Vello Celular? Apostas Ao Vivo Posso Fazer Login No Now, you have a chance to experience the game’s fact without any economic risk through the particular Plinko free type. Yes, Plinko Trial is ideal with regard to learning the game’s mechanics, experimenting together with risk levels, plus practicing strategies with out spending real funds. You can perform the Plinko demonstration in this article on our platform, completely free in addition to without the need to register. This demo version lets you explore the video game, test its mechanics, and luxuriate in the enjoyable without any monetary commitment. Our risk plinko demo gives a clean, user-friendly software designed for brand new users. The structure is simple and intuitive, letting you start actively playing immediately.

  21. FrankGlora表示:

    top 10 online pharmacy in india: india online pharmacy – USA India Pharm

  22. dragon money casino официальный сайт http://www.dragon-money33.com/ .

  23. Waltonnix表示:

    Online medicine home delivery: Online medicine order – cheapest online pharmacy india

  24. My brother suggested I would possibly like this
    web site. He used to be totally right. This publish actually
    made my day. You can not believe just how a lot time I had spent for this info!

    Thanks!

  25. SamuelSmity表示:

    Medicine trends available. https://edpillrx.top/# Drug essentials explained. ed pills comparison

  26. Seong-Ok.Kr表示:

    Its such as you learn my thoughts! You appear to understand a lot approximately
    this, like you wrote the book in it or something. I feel that you just could
    do with some percent to pressure the message home a little bit, but instead of that, this is fantastic blog.
    A great read. I will definitely be back.

    Also visit my web blog: Seong-Ok.Kr

  27. Bradley表示:

    Total should you take the Anavar-X we recommend (which
    isn’t truly Anavar) you can get the identical outcomes, without any of the legal points, AND with
    minimal side effects and just all pure features. Thus, by growing your
    endogenous ATP production, Anavar will allow you to push your
    limits within the health club. But ask anybody who has taken this
    drug earlier than a exercise, and you’ll realize how useful its strength-boosting results may be.
    That is due to its capability to extend your body’s ATP (adenosine triphosphate) production. As you might already know, ATP is the
    energy-carrying molecule in your physique cells.
    It’s responsible for giving your body the gasoline
    to perform each single exercise you do each second of every single day.

    Taking 4 grams of fish oil per day has helped some
    of our patients stabilize their blood strain (3). Water retention is nearly certain with this duo,
    inflicting users bloating and muscle smoothness. Subsequently,
    we see this cycle generally taken in the course of the off-season when a person is optimizing for mass as a substitute of aesthetics.
    This means customers solely must inject once each 4–5 days, yet they will experience the same gains at the
    end of a cycle in comparability with the quicker esters.

    As soon as our patients start to experience the early levels of gynecomastia, they start operating letrozole at
    the dosages said above. This is undesirable information, considering blood stress
    is already prone to be excessive during this
    cycle. Gynecomastia is possible on this cycle due to the testosterone aromatizing.
    Thus, high estrogen ranges might trigger breast tissue to enlarge in males.
    When taking this cycle, it’s attainable to expertise problem urinating,
    which may indicate prostate enlargement. In some cases, when these situations are left untreated, they can result in severe well being points and even demise.

    Regarding Anavar for ladies, virilization, or the event of male intercourse
    traits, can occur with larger doses of Anavar
    (19). These unwanted side effects include physique hair growth, clitoral enlargement
    and deepening of the voice. To prevent virilization, a starting Anavar cycle for women begins with just 5-10mg and will increase from there.
    Oral steroids like Anavar are commonly known for producing a workout/steroid “pump,” which is an impact that is created by the elevated
    quantity of pink blood cells within the physique. This elevated blood volume helps carry extra oxygen all through one’s physique and
    makes them feel more energetic.
    Some work together harmfully with particular medications or alter their effectiveness.
    Worse but, lately regulators have found that tons of of supplements are tainted with prescription drugs and other
    potentially dangerous chemicals. Anavar is used to help
    individuals regain weight lost after surgery, extreme trauma, or
    continual infections. Anavar can additionally be used in individuals who can not gain or maintain a healthy weight for unknown medical causes.
    In addition, Anavar can be used to decrease muscle loss triggered through the use of steroid medicines and to scale back bone pain in folks with osteoporosis.

    Powerlifters can benefit from the use of Anavar, however only when used responsibly and with caution. It is essential to follow the really helpful Anavar dosage and cycle tips
    and monitor the body’s response to the drug carefully.

    Session with a medical professional earlier than use is very recommended.

    Increase In Energy – customers expertise distinctive
    levels of power when taking anavar, making it probably the greatest
    steroids to take if you’re attempting to set new PR’s
    in the fitness center. Because anavar can construct muscle
    and scale back body fats simulatenously, while having minimal side effects; it’s easy
    to know why fitness center rats are popping var tablets
    like they’re candy. Anavar can have an effect on levels of cholesterol by reducing HDL or ‘good cholesterol’ and rising LDL ‘bad cholesterol’.

    Clenbuterol is utilized by bodybuilders as a result of its stimulating results on metabolism.
    Testosterone will produce significant increases in muscle hypertrophy and strength,
    hence why it’s referred to as a bulking steroid. The follow-up cycle to this commonly begins with a
    dose of 20 mg as a substitute of 15 mg and is prolonged up to
    eight weeks. Based Mostly on our observations, ladies usually engage in Anavar-only cycles,
    whereas males with prior steroid use are extra inclined to mix Anavar with
    different substances.
    Figuring Out the correct dosage of Anavar is crucial for maximizing its benefits whereas minimizing potential
    side effects. For male athletes and bodybuilders, the standard dosage ranges from 20 to 100 mg per day.
    Novices are suggested to begin out on the decrease end of this vary to evaluate
    tolerance, steadily growing the dose as their body
    adapts.
    Girls ought to train caution and contemplate milder options with fewer androgenic properties.
    In essence, Anavar can wear quite a few hats in your bodybuilding routine,
    from performing as a kickstarter to becoming a vital part of mixed cycles.

    However, all the time keep in mind that it’s not about pushing the limits however
    about sustaining a balance. This is the street to achieving your dream physique confidently
    and healthily, with Anavar as your trustworthy sidekick.
    Anavar for girls is a robust ally in the pursuit of an ideal physique,
    but solely when wielded with knowledge and intent. Finally, advanced bodybuilding is a mix
    of experience, self-discipline, and exact understanding of
    your physique. The Anavar chopping phase is an important a half of this puzzle and should be approached with intent and
    data.
    Anavar is an oral steroid, thus some of the drug has to pass via the liver before coming
    into the bloodstream. This may cause some stress on the liver, nonetheless, this effect is considered delicate, as a outcome of
    steroid additionally being metabolized by the kidneys.
    A PCT is not typically used to help restore testosterone levels from an anavar-only cycle,
    as most individuals tolerate the drug very well. Anavar is a comparatively
    gentle steroid, in comparability with other AAS similar to trenbolone or anadrol.
    Nevertheless, anavar’s a banned substance and is unlawful to purchase in many nations –
    with no prescription (including US and UK).
    Like all AAS, Anavar will positively affect your restoration, speeding up
    tissue healing. With its recognized benefits on collagen synthesis (after all, Anavar was initially developed
    to promote healing), it can scale back soreness and ache
    post-workout. This may cause the blood strain to rise to harmful ranges,
    placing the person in danger for a heart assault or stroke.

    As a result, those with hypertension ought to be very
    cautious when contemplating utilizing Anavar.

    References:

    steroid trenbolone (Bradley)

發佈回覆給「WebSite - i8」的留言 取消回覆

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