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,675,372 Responses

  1. JosephCrimi表示:

    This article will tell you in more detail how to register with 1xBet with a promotional code http://cs-headshot.phorum.pl/viewtopic.php?p=595327#595327

  2. Gregoryron表示:

    olympe casino avis: olympe casino cresus – olympe casino avis

  3. RobertPaymn表示:

    Остеопатическое лечение: принципы, методы и показания
    Остеопатия — это направление медицины, основанное на целостном подходе к организму. Она рассматривает тело как единую систему, где дисфункция одного элемента влияет на другие. Остеопатическое лечение направлено на восстановление баланса, мобилизацию внутренних ресурсов и устранение причин заболеваний, а не только их симптомов.
    остеопаты
    1. Основные принципы остеопатии
    Остеопатия базируется на трех ключевых принципах:
    1. Единство тела – все органы, мышцы, кости и нервы взаимосвязаны.
    2. Структура и функция – нарушение анатомии (смещение, напряжение) ведет к дисфункции органа.
    3. Саморегуляция – организм способен самовосстанавливаться при правильном воздействии.

    2. Методы остеопатического лечения
    Остеопатия включает несколько направлений:
    Структуральная остеопатия
    • Работа с опорно-двигательным аппаратом (суставы, позвоночник, мышцы).
    • Применяется при остеохондрозе, сколиозе, болях в спине, последствиях травм.
    Висцеральная остеопатия
    • Воздействие на внутренние органы (печень, почки, желудок).
    • Помогает при нарушениях пищеварения, спайках, застойных явлениях.
    Краниосакральная терапия
    • Коррекция ритмов черепа и крестца.
    • Используется при мигренях, бессоннице, неврозах, последствиях родовых травм.

    3. Показания к остеопатическому лечению
    • Лечение заболеваний позвоночника (грыжи, протрузии, радикулит).
    • Лечение головных болей и мигрени.
    • Лечение нарушения осанки (сколиоз, кифоз).
    • Лечение болезней суставов (артроз, артрит).
    • Лечение проблем ЖКТ (запоры, дискинезия желчевыводящих путей).
    • Лечение последствий травм (переломы, растяжения, ДТП).
    • Лечение приинекологических нарушениях (болезненные месячные, спайки).
    • Лечение при неврологических расстройствах (бессонница, ВСД). Лечение синдром хронической усталости (выгорание, стрессы).

    4. Как проходит сеанс остеопатии?
    1. Диагностика – врач остеопат руками определяет зоны напряжения и дисфункции.
    2. Коррекция – мягкие мануальные техники (без резких движений!).
    3. Рекомендации – советы по образу жизни, упражнениям.
    Длительность: 40–60 минут.
    Курс: обычно 3–8 сеансов с интервалом в 1–2 недели.

    5. Противопоказания
    ? Острые инфекции (температура, воспаление).
    ? Остеопороз в тяжелой форме.
    ? Опухоли, тромбозы.
    ? Психические расстройства.

    6. Остеопатия для детей
    Особенно эффективна при:
    • Лечение родовых травмах.
    • Кривошее.
    • Лечение гиперактивности (СДВГ).
    • Лечение при задержке развития.

    7. Отличие остеопатии от мануальной терапии
    Критерий Остеопатия Мануальная терапия
    Подход Целостный, мягкий Локальный, жесткий
    Техники Безболезненные Может быть дискомфорт
    Цель Устранение причины Снятие симптомов

    8. Вывод
    Остеопатия – безопасный и эффективный метод лечения, который помогает не только при болях в спине, но и при многих хронических заболеваниях. Главное – выбрать квалифицированного специалиста с медицинским образованием.

  4. AlbertShund表示:

    https://olympecasino.pro/# olympe casino avis

  5. Ronaldbet表示:

    olympe casino cresus olympe casino en ligne

  6. free Poker表示:

    Look at my web page :: free Poker

  7. VictorVal表示:

    casino olympe: olympe casino en ligne – olympe casino avis

  8. Does your website have a contact page? I’m having trouble locating it
    but, I’d like to send you an email. I’ve got some creative ideas for your blog you
    might be interested in hearing. Either way, great website and I look forward to seeing it expand
    over time.

  9. hd pron clips表示:

    Top quality HD clips are crucial for any type of porn lover.

  10. Thus, some people may experience vital hair loss from a
    low dose of Anavar. Whereas others might experience
    no hair loss while taking excessive doses of trenbolone.
    We help our patients move from wellness to greatness, and live the happier, more healthy, and more productive lives they deserve.
    EVOLVE is the nation’s chief in Bioidentical Hormone Substitute and Peptide therapies.
    Usually, Oxandrolone (Anavar) is just given over the course
    of a interval of some weeks. You should at all times take your
    medication as prescribed by your doctor.
    If you are utilizing Anavar, you will want to follow a correct PCT protocol to guarantee that you keep the gains you may have made and avoid any negative side effects.
    If you’re considering taking Anavar, you might be
    questioning how it will have an result on your blood check
    results. Anavar, also known as oxandrolone, is a synthetic anabolic
    steroid that is typically used for slicing cycles.
    It is known for its ability to promote muscle progress
    and fats loss, making it a preferred selection amongst bodybuilders and
    athletes.
    Therefore, if Anavar is taken with the intention of bulking and gaining lean mass, then a small calorie surplus may
    be adopted to reinforce muscle and energy outcomes. Clenbuterol’s unwanted side effects will virtually
    certainly diminish post-cycle. Anavar’s testosterone-suppressing effects, nevertheless, can linger for several months.

    We have discovered clenbuterol to cause cardiovascular strain in some
    customers, probably causing myocardial injury (33). This is as
    a result of of extreme stimulation of the CNS, causing increased levels of
    epinephrine. Consequently, a user’s heart fee can pace up
    and turn out to be enlarged (34). Pharmaceutical-grade Anavar has been leaked onto the black market by way of special connections.

    It could be effective when taken alone however is usually stacked with different steroids
    for higher outcomes. Anvarol from Loopy Bulk is one such authorized alternative that not
    solely delivers on its guarantees but also trumps Anavar in phrases
    of results. It’s comparatively delicate, so it doesn’t include too many dangers,
    and it may possibly assist you to obtain your goals faster than should you were to go on a food
    regimen and exercise plan alone. Nonetheless, everyone seems to be totally
    different and a few individuals might expertise harsher unwanted effects than others.

    By making knowledgeable decisions, in search of steering, and following finest practices, you can optimize your Anavar expertise and work
    in direction of attaining your required health and efficiency goals.
    Oxandrolone is renowned for its ability to contribute
    to varied fitness targets, including muscle definition,
    power enchancment, enhanced endurance, and fats loss. This
    table supplies a comparison of Anavar’s results on these key elements, supplying you with
    an summary of the potential benefits it presents. Please observe that
    particular person results might vary, and it is crucial to make use of Anavar responsibly
    and beneath professional steering. Anavar is primarily taken orally, a key distinction from many
    injectable anabolic steroids.
    As a result of both of these advantages, you’ll be
    able to have a better time constructing lean muscle.
    Before seeking a prescription for Anavar, it’s necessary to have a thorough dialogue with your doctor about your medical historical past and health targets.
    This will assist be sure that Anavar is the proper possibility for you and that it can be safely prescribed.
    One Other option for acquiring an Anavar prescription on-line is through online pharmacies.
    These pharmacies let you purchase medications, together with Anavar, and not using a prescription.
    Nonetheless, you will need to note that using anabolic steroids,
    together with Anavar, for non-medical purposes is in opposition to the law in plenty
    of nations and might have critical well being risks. Anavar is an anabolic steroid that
    is usually used by bodybuilders and athletes to extend
    muscle mass and improve athletic performance. Anavar is
    understood for its ability to extend strength and endurance,
    making it a popular selection for athletes who need to carry out at a high level.
    It can also help to extend muscle measurement and definition, making it a popular alternative for
    bodybuilders. In abstract, PCT is an important course of that bodybuilders and athletes undergo after finishing a cycle
    of anabolic steroids. It helps to revive the body’s pure hormone manufacturing and scale back
    the chance of unwanted facet effects.
    Look for well-reviewed and established manufacturers, also recognized
    as UGLs (Underground Labs). Popular names like Pharmaqo,
    Alpha Pharma, Dragon Pharma, and Meditech tend to offer more reliable merchandise.
    Buying poor-quality Anavar isn’t only a waste of money—it can compromise your well being
    and your results.
    Take benefit of our free-shipping choices, which is at all times fast, safe,
    discreet. Anavar could be stacked with other steroids corresponding to Winstrol, Clenbuterol, and Trenbolone to boost its effects.
    Nonetheless, it is essential to consult with a healthcare professional earlier than stacking any steroids to keep away from antagonistic effects.
    Anavar can help you raise heavier weights, which can help you construct extra muscle mass and increase your general power.
    Additionally, Anavar can help you recover extra rapidly between workouts,
    which may help you prepare harder and more incessantly.
    One of the explanation why Anavar is so in style is as a end result
    of it’s a relatively safe steroid. Furthermore, the line between legal purchase
    and potential authorized points could be very thin.
    Beyond our concentrate on high quality and affordability,
    Mexican Pharmacy On-line is committed to making the net buying process as simple
    and seamless as potential. Our web site is designed to be straightforward to navigate,
    allowing customers to shortly discover and order the medicines they need from home.
    With just a few clicks, they will place an order, apply available discounts, and have their medicines
    delivered straight to their door. To ensure a secure and safe buying experience, we use superior safety measures to protect
    customer data at each step. Hormones function essential communicators within the physique,
    and Oxandrolone leverages this by enhancing sure biochemical pathways that underlie well-being.

    References:

    can prednisone cause heavy periods

  11. Gregoryron表示:

    olympe casino cresus: olympe – olympe casino

  12. mostbet_xuea表示:

    скачат мостбет http://mostbet7004.ru .

  13. Oh my goodness! Amazing article dude! Thank you, However I am encountering problems
    with your RSS. I don’t understand why I cannot join it.
    Is there anybody else having the same RSS problems?
    Anybody who knows the solution can you kindly
    respond? Thanx!!

  14. Louisveige表示:

    This guide explores the core SEO strategies needed to increase visibility for your gambling app, attract more users, and improve your rankings BLACK SEO LINKS, BACKLINKS, SOFTWARE FOR MASS BACKLINKING – TELEGRAM @SEO_LINKK

  15. Medicines information leaflet. Cautions.
    how to get nolvadex online
    Some news about meds. Get here.

  16. Diplomi_apMl表示:

    купить готовый диплом новосибирск rusdiplomm-orig.ru .

  17. safe steroids表示:

    While generally thought of one of many milder anabolic steroids, Anavar can still carry some risks if not used responsibly.
    These days you ought to buy legal steroid options on-line, with manufacturers claiming
    to recreate the consequences of anabolic steroids; but with little to no unwanted aspect effects.
    We don’t imagine such supplements are as highly effective as real anavar, however they won’t pose the identical harmful
    unwanted facet effects as oxandrolone. Look for anabolic steroids with least unwanted effects to minimize well
    being dangers and discover the most secure steroid cycle that suits your
    targets and health needs. Anavar was initially developed to
    assist sufferers recover weight after medical trauma, such as surgical procedure or an infection. Over time,
    its advantages for muscle constructing and fat loss captured the eye of bodybuilders and athletes.
    This is because of Anavar being 5α-reduced; thus, it does
    not aromatize, which means estrogen ranges remain steady.

    The combination of high estrogen ranges and sodium-rich diets
    is what causes bloating. Anadrol is estrogenic, in distinction to Superdrol, thus inflicting vital quantities of weight achieve
    in the type of lean muscle and water retention. Superdrol isn’t stacked with different steroids as a end
    result of its severe opposed results.
    This can be what we see anecdotally, and thus we warn our
    readers from using such a stack. Liver toxicity is going to be extra significant in the presence of Anadrol, an oral steroid that is C17-alpha-alkylated.
    This is undesirable information, considering blood pressure is already
    prone to be excessive during this cycle. Gynecomastia is feasible
    on this cycle because of the testosterone aromatizing.
    Thus, excessive estrogen levels may trigger breast tissue to enlarge in males.

    When taking this cycle, it’s possible to
    expertise issue urinating, which may indicate prostate enlargement.
    Thus, the outlined PCT have to be implemented to kick-start endogenous testosterone back to regular
    levels again.
    This complete evaluation delves into the essence of Anavar, dissecting its components, functionalities,
    and the general experience it offers to users. Proper Dosage and DurationAdhering to beneficial
    dosage guidelines and cycle duration is significant
    for minimizing the chance of side effects. Beginning with a
    decrease dose and progressively growing it over
    time permits the physique to adapt to the
    compound. It is crucial never to exceed the beneficial dosage
    as it may significantly improve the possibilities
    of opposed results. Primobolan is an orally energetic
    anabolic steroid that binds to and stimulates Androgen Receptors
    within the muscle tissue.
    Anti-estrogen medications usually are not wanted,
    as Oxandrolone doesn’t aromatize. In Canada, Oxandrolone
    can also be a managed substance categorized as Schedule IV beneath the Controlled Medicine and Substances Act.
    Similar to the United States, it’s legal to possess and use Oxandrolone with a valid
    prescription from a licensed healthcare professional for accredited medical purposes.
    While Oxandrolone is typically used by female, the
    PCT process for girls may differ as a result of differences in hormone regulation. Women should consult with a certified healthcare service
    for proper PCT. Women at our clinic have reported a gentle downturn in power, libido, and fatigue following an Anavar cycle.

    With its recognized advantages on collagen synthesis (after all,
    Anavar was initially developed to advertise healing), it could possibly cut back soreness and pain post-workout.
    As a therapy for anemia, Anavar has a very helpful impact on red blood cell count21,
    bringing about heightened endurance by transporting extra oxygen and vitamins
    to the muscles during exercise. This has a performance-enhancing
    and physically interesting impact, with extra oxygen and blood being carried through the veins,
    leading to enhanced vascularity.
    Nonetheless, keep in thoughts that Anavar is a prescription drug,
    and using it without professional guidance poses serious well being dangers.
    Informed individuals verify product certificates and seek
    the guidance of with specialists earlier than buying.
    Moderation and ongoing monitoring of your well being
    are the backbone of a accountable Anavar cycle.

    Anavar (oxandrolone) is a popular anabolic steroid utilized by many people for different reasons.

    Whereas it’s often praised for its muscle-building benefits, knowing
    how it works might help folks avoid the dangers concerned with its use.
    Anavar’s producers will at all times label it for use as directed by your physician; nonetheless, most people utilizing it do not check into the physician’s workplace.

    In the United States, the typical retail value for Oxandrolone is round $4-5 per 2.5mg pill from authorized pharmacies with a legitimate prescription. For a typical 6-8 week cycle at 20-40mg per
    day, the entire price can range from $200-$800. Unauthorized
    possession or use of Oxandrolone for non-medical reasons can lead
    to criminal charges and penalties, including fines and doubtlessly imprisonment.
    In the United States, Oxandrolone is a managed substance categorized as Schedule III underneath the
    Managed Substances Act.
    With Anavar additionally being a costly compound, this cycle can price hundreds of dollars.

    This is a typical follow-up cycle to the primary Anavar and testosterone cycle listed.
    If the steroid is stopped soon sufficient, these effects should reverse and go away.
    But if Anavar continues for use, it might be more durable to reverse or deal with virilization effects the more they’re allowed
    to develop. Notice that this doesn’t necessarily mean it’s authorized to import or sell AAS in such countries –
    laws differ.
    However, possessing or utilizing Oxandrolone and not using a prescription for non-medical reasons, corresponding to bodybuilding or athletic performance enhancement,
    is taken into account unlawful. Penalties for illegal possession or distribution can range depending on the quantity and the precise circumstances, starting from fines
    to potential imprisonment. When adopting a dosage of 10 mg/day for 5 weeks, the
    risk of developing masculinizing side effects could also be decrease due to the modest dose and shorter cycle period.
    Wait 14 days submit cycle to begin restoration and use 50mg/day Clomid for 20 days and zero.5mg/day
    Arimidex alongside it.
    We have seen this cycle add large amounts of measurement and strength in intermediate steroid users.
    Anadrol is probably the worst steroid for blood stress, causing
    hefty rises as a result of its disastrous impact on HDL levels of cholesterol.
    This is because of it stimulating hepatic lipase, an enzyme liable for reducing good ldl cholesterol
    (HDL), which prevents clogging of the arteries.

    References:

    safe steroids

  18. Iariorwzn表示:

    Приобрести диплом ВУЗа по выгодной стоимости можно, обратившись к надежной специализированной фирме. Приобрести документ университета вы сможете у нас в Москве. diplomidlarf.ru/kupit-diplom-s-zaneseniem-v-reestr-bistro-i-prosto-10

  19. Iariorluj表示:

    Приобрести диплом ВУЗа по выгодной цене можно, обратившись к проверенной специализированной фирме. Купить документ ВУЗа вы можете у нас в столице. diplomh-40.ru/kupite-diplom-o-visshem-obrazovanii-bez-lishnix-problem-2

  20. Ronaldbet表示:

    olympe casino cresus olympe casino

  21. Diplomi_joMl表示:

    куплю диплом специальности куплю диплом специальности .

  22. Mia Melano sex video, not as well shoddy.

  23. mostbet_ozea表示:

    mostbet официальный сайт mostbet7004.ru .

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

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