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,373,936 Responses

  1. DanielAbice表示:

    https://amoxstar.com/# amoxicillin price without insurance

  2. In the USA, it’s illegal to utilize HGH for a condition that isn’t accepted by the Fda. So, it’s against the legislation to utilize HGH for developing muscle mass or as an anti-aging treatment. Some individuals make use of the hormone, in addition to other performance-enhancing drugs such as anabolic steroids, to develop muscular tissue and boost athletic performance.
    Target Information For Development Hormone 1
    Ultimately, the viability of the peptide structure for docking was evaluated using the Ramachandran plot function in Exploration Studio Visualizer. Researchers don’t have sufficient info regarding the long-lasting effects of HGH therapy. Research study shows that the GHRH pathway creates HGH secretion throughout rest. Moreover, this mechanism induces the creation of somatostatin, frequently known as Growth Hormone-Inhibiting Hormone or GHIH. This peptide hormonal agent controls the endocrine system and limits insulin and glucagon launch.
    How Long Does Growth Hormonal Agent Take To Work?

    While HGH may be viewed by some as a much safer alternative to steroids, it’s essential to understand that both substances pose considerable health dangers. Neither must be used without the close guidance and tracking of a qualified doctor. The best outcomes will certainly include treatments carried out for months and occasionally years to optimise your body’s all-natural manufacturing of HGH degrees. If you have certain problems about aging, ask your medical care specialist about tested ways to increase your health.
    Experience With Utilizing Hgh
    Somatropin is a type of human development hormone vital for the growth of bones and muscles. Scientists offered a group of men an amino acid supplement called arginine to see exactly how it affected their hormones. They found that arginine increases growth hormone, however they will certainly require to do even more researches to discover this impact.
    Nonetheless, it’s most popular for its growth-promoting result on cartilage and bone, specifically in the adolescent years during puberty. Cells in cartilage called chondrocytes and cells in bones called osteoblasts get signals from HGH to raise duplication and therefore allow for growth in dimension. Tell your medical professional if you have actually ever before had any uncommon or allergic reaction to medicines in this group or any type of various other medications. Also tell your healthcare expert if you have any other kinds of allergies, such as to foods dyes, preservatives, or pets. For non-prescription items, checked out the tag or plan components very carefully.

    Very rapidly, performance-enhancing drugs (PEDs) became the standard for body builders and athletes who were attempting to press the limits of their bodies. There’s little study to suggest that HGH can help otherwise healthy and balanced grownups regain young people and energy. What’s more, HGH treatments might increase the risk of other wellness problems. Specialists advise versus utilizing HGH to deal with aging or age-related conditions.
    Accomplishing the very same IGF-1 induction with reduced product GH degrees has the potential to maintain efficacy of therapy while reducing the threat of negative effects because of the straight activities of hGH. Specifically, offered the increasing occurrence of diabetes mellitus, there is raising worry of GH’s results on insulin level of sensitivity (41 ). Certainly, an evaluation of information from the Pharmacia KIGS postmarketing monitoring data source located a raised incidence of diabetic issues in youngsters treated with GH substitute treatment (42 ).
    Some people report that sermorelin makes them really feel starving, yet there is no proof as to whether it is the injection, a requirement to take it on an empty tummy, or an additional factor at the office. A person can consume alcohol water to help in reducing their appetite up until they can eat. In the United States, you can just obtain injectable HGH legitimately with a prescription from a medical professional. Obtaining HGH using a prescription is a method that helps to make certain that your HGH is risk-free and legitimate. Nourishment influences GH secretion and it varies between fasting and fed problems.
    Human Growth Hormonal Agent (hgh) In Bodybuilding: A Thorough Overview

    Researches reveal that synthetic human growth hormone may increase sexual efficiency. It can aid men with things like obtaining an erection, and might additionally boost females’s sexual function, however it is not FDA-approved for this use. Human growth hormone (HGH), additionally called somatotropin, is a hormone that the pituitary gland, which is about the size of a pea and discovered at the base of your brain, makes and releases. The pituitary gland has two parts– a front (former) and a back (posterior) wattle.
    This disease is extremely comparable to acromegaly in all facets, except the underlying pituitary adenoma develops prior to the closure of long bone epiphysis. For that reason, bone development happens in lengthy bones such as the tibia, fibula, femur, humerus, span, and ulna. Since epiphyseal closure happens prior to their adult years, this is typically an illness with a start seen in youngsters. HGH is very important for regulating growth during teenage years. Therefore, the major aberrations in the policy of HGH may result in growth defects. HGH hypersecretion causes gigantism or acromegaly, whereas HGH deficiency will certainly cause a development deficiency in youngsters and the GH deficiency disorder in grownups.
    Benefits Of Hgh191aa Somatropin Peptide Vial:
    ” And besides, any kind of medication not checked or authorized by FDA is high-risk because it is unknown and not necessarily secure, pure, sterilized, or what is being promoted.” HGH has actually likewise gotten a track record as a muscular tissue home builder, and its usage is outlawed in the Olympics and various other sporting activities. Nevertheless, there is little solid proof that it can boost athletic performance. Some of the possible restrictions of the research study are its failure to currently conduct any kind of morphological studies, entrapment performance, along with in-vitro launch research study. Cells were treated and feasibility gauged as defined in Number 4. Cytotoxicity of the different Chitosan nanoparticle solutions versus MCF-7 cells.

  3. Nikefut表示:

    deep web drug markets dark web market list blackweb

  4. Robot Broom表示:

    10 Quick Tips About Smart Vacuum Cleaner Robot Broom

  5. Edward Willis表示:

    The variety of plumbers listed on top plumber directories is impressive—I found exactly what I needed!

  6. Earl Jensen表示:

    I’ll always advocate using professionals who truly underst Property safety inspection Puerto Rico

  7. If you’re in Orange County and need data recovery mac data recovery

  8. DanielAbice表示:

    https://amoxstar.com/# can i buy amoxicillin online

  9. pornhub china表示:

    Very great post. I just stumbled upon your blog and wanted to mention that I have really loved browsing your weblog posts.

    After all I’ll be subscribing in your feed and I am hoping you write once more soon!

  10. Appreciate the thorough insights. For more, visit cake shop near me

  11. There are various tools and websites that claim to permit users to view private instagram pictures private Instagram profiles, but it’s important to
    get into these taking into account caution. Many of these
    tools can be unreliable, may require personal information,
    or could violate Instagram’s terms of service.
    Additionally, using such tools can compromise your own security or lead to scams.
    The safest and most ethical pretentiousness to view a private profile is to send
    a follow request directly to the user. Always prioritize privacy and adulation in your online interactions.

  12. Estrogen levels should return to regular levels, and gynecomastia should
    be decreased.

  13. SamuelBix表示:

    can i buy generic clomid without prescription: where to buy generic clomid – where can i buy cheap clomid without insurance

  14. Nikefut表示:

    tor darknet deep web drug markets dark markets 2024

  15. Yes! Finally something about apply evisa.

  16. DanielAbice表示:

    https://prednibest.com/# prednisone 10 mg brand name

  17. Thank you for the good writeup. It in fact was a amusement account it.
    Look advanced to more added agreeable from you!
    However, how could we communicate?

  18. KennethPah表示:

    buy generic ciprofloxacin buy cipro without rx buy ciprofloxacin

  19. DanielAbice表示:

    https://amoxstar.com/# purchase amoxicillin online without prescription

  20. Russellvak表示:

    The 1xBet promo code 2025: 1XNEW25. Use to register a new member, get a sports bonus 100% up to €130 and casino bonus €1950 + 150 free spins. Use the bonus code when registering and you are guaranteed to receive a 2025 welcome bonus from 1xBet. The 1xBet bookmaker has proven itself to be time-tested, it has high odds for sports betting, and a huge number of slots in the cauldron section, there are also roulette, poker, and fast online games like Aviator.

    https://juvalife.com/pag/free_1587.html – 1xbet official promo code bangladesh

  21. Shaneevige表示:

    Useful info. Fortunate me I discovered your web site unintentionally, and I’m shocked why this twist of fate didn’t came about in advance! I bookmarked it.

    https://sasquatchchronicles.com/pgs/le-code-promo-1xbet_bonus.html

  22. ThelmaFange表示:

    On our website you will find a unique assortment rare coins from all over the world. We offer both modern and historical specimens that will become real finds for collectors.
    For more information, follow the link [url=https://numizmatexpert.ru/]полкопейки [/url]
    Our team of experts carefully selects each coin, ensuring high quality.

  23. Lamarmag表示:

    Активный живой блог про любовь L28.Ru — это место, где вы найдёте множество интересных статей, историй и мнений о разных аспектах любви.
    https://l28.ru/ – Любовь

發佈留言

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