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,684,240 Responses

  1. Michaelguite表示:

    напольная видеостена http://videostena-1.ru

  2. sunda表示:

    I absolutely love your website.. Excellent colors & theme.
    Did you create this site yourself? Please reply back as I’m attempting to create my own website and
    want to find out where you got this from or just what the theme is named.
    Thank you!

  3. Williamwhogs表示:

    olympe casino avis: olympe casino – olympe casino en ligne

  4. When exploring AI content tools, it’s important to know which platforms allow or restrict NSFW content. Whether you’re working on artistic projects or adult-themed applications, make sure to choose tools that align with your content policies.

  5. koitoto表示:

    Howdy! I could have sworn I’ve been to this blog before but after going through many of the articles I realized it’s new
    to me. Anyways, I’m certainly delighted I found it and I’ll be book-marking
    it and checking back regularly!

  6. Ronaldbet表示:

    olympe casino casino olympe

  7. Gregoryron表示:

    olympe casino cresus: olympe casino cresus – olympe casino en ligne

  8. Mazrntj表示:

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

  9. fuck表示:

    This paragraph offers clear idea for the new people of blogging, that actually how to do blogging and
    site-building.

  10. Williamwhogs表示:

    olympe casino: olympe casino cresus – casino olympe

  11. Ctpedia.org表示:

    Whether it is a kitchen or bath remodel or a major addition, Dave and
    his team give you the same quality and craftsmanship you deserve.

  12. Sazravl表示:

    Приобрести диплом возможно используя официальный сайт компании. office.listbb.ru/viewtopic.phpf=2&t=7222

  13. mostbet_qzEi表示:

    mostbet официальный сайт http://mostbet5010.ru .

  14. Rabyemert表示:

    dark web market list dark web link

  15. Diplomi_xyMl表示:

    диплом мгу купить диплом мгу купить .

  16. Ronaldbet表示:

    olympe olympe casino cresus

  17. 1win_wlPt表示:

    1win casino mexico 1win1008.top .

  18. Ronaldbet表示:

    casino olympe olympe casino en ligne

  19. Williamwhogs表示:

    olympe: olympe – casino olympe

  20. Премиальные шторы на заказ для вашего интерьера, для вашего дома.
    Качественные шторы на заказ, с гарантией качества.
    Изготовление штор на заказ, по вашим размерам.
    Шторы на заказ с доставкой, подчеркивающие ваш стиль.
    Заказать шторы на заказ для спальни, с учетом модных трендов.
    Индивидуальный дизайн штор, под любой бюджет.
    Создание штор на заказ из натуральных тканей, используя современные технологии.
    Шторы на заказ с уникальным дизайном, от профессионалов.
    Современные шторы на заказ, по вашему проекту.
    Шторы на заказ с учетом ваших пожеланий, по вашему стилю.
    Креативные шторы на заказ, воплощая ваши идеи.
    Изготовление штор на заказ быстро и недорого, с высоким качеством.
    Стильные шторы по вашему проекту, от ведущих дизайнеров.
    Дизайнерские шторы на заказ, по вашему проекту.
    Пошив штор по индивидуальному дизайну, под ваш вкус.
    Пошив штор на заказ с индивидуальным подходом, под любой стиль.
    сшить шторы на заказ сшить шторы на заказ . Прокарниз

  21. Security ought to be a prime priority when using any performance-enhancing drug, and Oxandrolone is no
    different. It’s beneficial to begin with a conservative dosage, typically within the range of 5 to
    10 milligrams per day. This permits your body to regulate
    and mitigate the chances of encountering opposed reactions.
    Monitor your body’s response closely and regulate the dosage if necessary—but stay throughout the affordable vary mentioned.

    To guarantee your safety and minimize potential side effects, it
    is crucial to contemplate the optimum period of an Anavar cycle for ladies.
    While it’s thought-about much less hepatotoxic in comparability with different
    oral steroids, stacking it with different orals or excessive alcohol consumption can elevate the danger of liver injury.
    ● Always contemplate in search of a doctor’s advice on the safe and efficient
    usage of steroids to prevent any negative effects on the physique.

    Anavar, too, may be stacked with other anabolic steroids; however, doing so will exacerbate side
    effects, leading to extra toxicity. Equally, ladies don’t need to fret about masculinization occurring on Anvarol, which we see happen on high
    doses of Anavar at our clinic. This often includes clitoral
    enlargement, irregular periods, a deepened voice, and hair growth on the physique.

    It’s necessary for girls to have sensible expectations
    when utilizing Anavar for weight loss. Some ladies may see dramatic ends in a relatively quick time, while others may expertise more gradual modifications.
    Patience and consistency are key, as sustainable
    fats loss takes time, even with the assist of a powerful compound like Anavar.
    When it comes to performance enhancement for girls, Anavar (Oxandrolone) usually stands
    out as a well-liked selection.
    For girls new to intense training or returning after a break,
    it’s advisable to ascertain a constant train routine earlier than starting an Anavar cycle.
    This approach allows for a better understanding of how
    the body responds to coaching alone, making it easier to establish the particular effects of Anavar when it
    is introduced. It Is essential to notice that the improved restoration and
    performance offered by Anavar should not be used as an excuse to overtrain. Whereas the steroid can masks fatigue and velocity up recovery, the
    physique nonetheless has limits that must be respected to forestall long-term harm or
    burnout. Mood swings and aggression, sometimes called
    “roid rage,” can happen with Anavar use, though sometimes to a
    lesser extent than with more potent steroids. Some girls might experience elevated irritability, anxiousness,
    or temper fluctuations.
    Anavar is an artificial androgen and anabolic steroid that is used in the therapy of anemia,
    as nicely as for increasing muscle mass and power.
    Although it has been historically used by males, women can even profit from its use.

    Effects on women’s physique and well being are nonetheless largely unknown, however there are some
    potential benefits that should be thought of. Anavar tends to have a relatively gentle anabolic effect
    in comparability with different steroids. For those who need to maximize
    their positive aspects, Anavar may be combined with Testosterone—a significantly stronger anabolic
    steroid. Testosterone is a naturally occurring hormone within the
    physique that performs a significant function in sustaining overall health
    and selling muscle growth.
    Some argue that due to the relatively delicate nature of Anavar and women’s naturally lower testosterone ranges, a proper PCT protocol is not
    required. Nonetheless, this view doesn’t account for the
    individual variations in response to Anavar or the potential for
    hormonal imbalances even with delicate steroid use. Training volume and depth can usually be increased when utilizing Anavar, due to its performance-enhancing effects.
    A typical routine may involve 4-5 weight training periods per week, targeting different muscle teams every session.
    A widespread method is to comply with a cycle with an off-period equal to or longer than the cycle size.
    For instance, a 6-week Anavar cycle could be adopted by no less than 6
    weeks off earlier than contemplating one other cycle. Women usually
    wrestle with cussed physique fats, notably in areas like the hips, thighs, and decrease stomach.
    Anavar has been shown to extend metabolic price
    and improve fats oxidation, making it an effective software for reducing body fat proportion.
    Many girls report increased confidence and motivation because of the enhancements of
    their physique and efficiency. This psychological boost could be a powerful consider maintaining consistency
    in training and diet, further amplifying the general results.
    Nonetheless, it is crucial to approach Anavar use with practical expectations and
    a transparent understanding of both its potential benefits
    and dangers. Compared to other anabolic steroids, Anavar is considered to have a lower potency in relation to promoting weight reduction.
    This is because its primary function just isn’t particularly associated to
    burning fat, however rather increasing protein synthesis and selling
    muscle development.
    Anavar will dramatically spike testosterone levels, while increasing
    protein synthesis and nitrogen retention. This shifts the body into an anabolic setting
    the place the body’s muscle-building potential will increase.
    Whereas Anavar is widely known for its use
    in sports activities and health, it additionally has medical applications.

    This lady misplaced about 20 lbs, was tight, and simply appeared wonderful from 10 mg/day
    of Anavar. Healthy males can keep away from these side-effects
    with proper preventative measures coupled with accountable supplementation. Anavar
    can suppress natural testosterone production however solely slightly as
    it has a mild effect on SHBG and LH and no impact on FSH.

    References:

    How Long Does It Take To Get Over Steroid Withdrawal?
    (https://Click4R.Com)

  22. Excellent content, Mia Khalifa 2024 XXX content is still appropriate.

  23. Williamwhogs表示:

    casino olympe: olympe casino cresus – olympe casino en ligne

  24. Diplomi_dxMl表示:

    купить диплом в нурсултане rusdiplomm-orig.ru .

  25. Ronaldbet表示:

    olympe olympe casino cresus

  26. Reasons Why Online Casinos Have Become an International Sensation

    Online casinos have transformed the gambling landscape, offering a level of user-friendliness and diversity that brick-and-mortar establishments can’t match. Over time, a large audience around the world have turned to the excitement of virtual gambling thanks to its always-open nature, exciting features, and constantly growing catalogs of games.

    One of the main appeals of online casinos is the unparalleled diversity of choices at your disposal. Whether you like rolling vintage reel games, diving into narrative-rich visual slot games, or playing smart in strategy-based games like Baccarat, casino websites feature numerous entertainment avenues. Several sites moreover feature live dealer games, enabling you to connect with human game hosts and opponents, all while enjoying the engaging atmosphere of a physical gaming house without leaving your home.

    If you’re a beginner with the world of virtual casino play or want to delve deeper into reputable operators, why not engage with our lively interactive platform? It’s a space where enthusiasts discuss experiences, helping you to get the most out of your online casino experience. Explore the connections and visit us now: vavada регистрация.

    Apart from the game range, digital casino services are known for ease of access.

  27. https://trifolafarmscbd.net/ take emerged as a popular select among consumers seeking the benefits of cannabidiol (CBD) in a handy and refined kind.

  28. Drugs prescribing information. Short-Term Effects.
    where to get generic tamoxifen online
    Actual trends of pills. Get information now.

發佈回覆給「Diplomi_dxMl」的留言 取消回覆

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