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,646,689 Responses

  1. FrankGlora表示:

    USA India Pharm: india online pharmacy – india pharmacy

  2. Georgeunula表示:

    indian pharmacy online: UsaIndiaPharm – top 10 pharmacies in india

  3. FrankGlora表示:

    Online medicine order: USA India Pharm – indian pharmacy paypal

  4. Natyazhnye потолки в Днепре , где качество встречает стиль, позаботьтесь о своем интерьере, выбор, который вас не разочарует.
    Премиум натяжные потолки в Днепре, инновационные технологии, которые создадут уют и гармонию, узнайте больше на сайте.
    Лучшие цены на натяжные потолки в Днепре, от natyazhnye-potolki-dnepr.biz.ua, оставьте позади скучные потолки, закажите бесплатную консультацию.
    Индивидуальный подход к каждому клиенту, доступные на natyazhnye-potolki-dnepr.biz.ua, превратите мечты в реальность, машина времени в мир красоты.
    Эстетика и функциональность натяжных потолков, отечественного производства, всё для вашего удобства, у нас широкий ассортимент.
    Почему стоит выбрать натяжные потолки?, от natyazhnye-potolki-dnepr.biz.ua, долговечность и надежность, обеспечьте себе комфорт.
    Как выбрать идеальный натяжной потолок?, всё на natyazhnye-potolki-dnepr.biz.ua, создайте уникальное пространство, заказ натяжного потолка стал проще.
    Натяжные потолки: легко и удобно, от natyazhnye-potolki-dnepr.biz.ua, доступные решения для каждого, обращайтесь к профессионалам.
    Создайте уют с натяжными потолками, с хорошей репутацией, поддержка и забота о клиенте, вдохните жизнь в ваше пространство.
    Лучшие предложения на натяжные потолки, от производителей, у нас отличный сервис и выбор, закажите натяжные потолки и наслаждайтесь результатом.
    Преобразите свое пространство с натяжными потолками, в Днепре, всегда профессионально, закажите свою консультацию.
    Ваш идеальный натяжной потолок, доступные на natyazhnye-potolki-dnepr.biz.ua, выбор, который вдохновляет, обратите внимание на наши предложения.
    Ваш надежный партнер в мире натяжных потолков, с индивидуальным подходом к каждому клиенту, креативные решения для любого интерьера, присоединяйтесь к нам.
    Мы поможем вам создать идеальный интерьер, в Днепре, выбор, который вас удивит, узнайте больше на нашем сайте.
    Эстетика натяжных потолков для вашего дома, от natyazhnye-potolki-dnepr.biz.ua, поддержка профессионалов на каждом этапе, воспользуйтесь нашим опытом.
    Натяжные потолки: качество и стиль, от надежных производителей, всё для вашего комфорта, не упустите шанс.
    тканевые потолки тканевые потолки .

  5. website here表示:

    With havin so much content and articles do you ever run into any problems of plagorism
    or copyright infringement? My blog has a lot of completely unique content I’ve either written myself or outsourced but it appears a lot of it is popping it up all over the internet
    without my permission. Do you know any ways to help protect against
    content from being stolen? I’d definitely appreciate it.

  6. Hello There. I found your blog using msn. This is a very well written article.
    I will make sure to bookmark it and return to read more of your useful info.
    Thanks for the post. I will definitely return. http://WWW.Pottomall.com/bbs/board.php?bo_table=free&wr_id=2599560

  7. Идеальные натяжные потолки в Днепре, где современные решения становятся реальностью, обновите свой дом, выбор, который вас не разочарует.
    Элегантные натяжные потолки для вашего дома, инновационные технологии, которые подчеркнут ваш стиль, закажите прямо сейчас.
    Лучшие цены на натяжные потолки в Днепре, по доступным ценам, придайте вашему интерьеру свежесть, сделайте выбор в пользу качества.
    Креативные решения для вашего интерьера, потолки, которые вдохновляют, превратите мечты в реальность, с нами это легко.
    Выбор натяжных потолков для любого стиля, по европейским стандартам, на любой вкус и цвет, на нашем сайте вы найдете именно то, что ищете.
    Натяжные потолки: преимущества и возможности, для вашего комфорта, вода не страшна натяжным потолкам, инвестируйте в качество.
    Эстетические решения для вашего потолка, где стиль и качество соединяются, превратите потолок в произведение искусства, заказ натяжного потолка стал проще.
    Натяжные потолки: легко и удобно, с нами легко и быстро, где ваши желания становятся реальностью, свой идеальный потолок в 3 шага.
    Качество натяжных потолков — наш приоритет, с хорошей репутацией, мы подберем потолок для любого интерьера, вдохните жизнь в ваше пространство.
    Натяжные потолки по доступным ценам, у надежных поставщиков, стиль, качество и цена — все в одном месте, не упустите свой шанс.
    Натяжные потолки: быстро и стильно, от natyazhnye-potolki-dnepr.biz.ua, всегда профессионально, позвоните и получите ответ на все вопросы.
    Ваш идеальный натяжной потолок, где стиль встречается с практичностью, выбор, который вдохновляет, обратите внимание на наши предложения.
    Ваш надежный партнер в мире натяжных потолков, с индивидуальным подходом к каждому клиенту, долговечность и стиль, обновите свой дом с нами.
    Мы поможем вам создать идеальный интерьер, с заботой о каждом клиенте, всё для вашего комфорта и стиля, узнайте больше на нашем сайте.
    Ваш потолок — ваша гордость, потолки для любого стиля, поддержка профессионалов на каждом этапе, закажите прямо сейчас.
    Дайте своему потолку вторую жизнь, где качество — превыше всего, мы создаем счастье для ваших глаз, свяжитесь с нами.
    установка натяжных потолков установка натяжных потолков .

  8. CarltonUnith表示:

    https://usaindiapharm.shop/# indianpharmacy com

  9. Click Here表示:

    I loved as much as you will receive carried out right here.
    The sketch is tasteful, your authored material stylish.

    nonetheless, you command get bought an nervousness over that
    you wish be delivering the following. unwell unquestionably come further formerly again as
    exactly the same nearly very often inside case you shield this hike.

  10. Starmcg表示:

    Получить онлайн консультацию психолога чате. Онлайн-консультация психолога. Получить КОНСУЛЬТАЦИЮ и ПОДДЕРЖКУ профессиональных психологов. оценили 748 раз

  11. pepek表示:

    I really love your website.. Great colors & theme. Did you build this site yourself?
    Please reply back as I’m attempting to create my own personal site and would like to know where you
    got this from or what the theme is named. Kudos!

  12. DavidSooni表示:

    Online medicine home delivery UsaIndiaPharm best online pharmacy india

  13. Mazrawx表示:

    Заказать диплом о высшем образовании!
    Мы оказываем услуги по изготовлению и продаже документов об окончании любых университетов РФ. Документы изготавливаются на настоящих бланках государственного образца. marleneblevins64.copiny.com/question/details/id/1084708

  14. idpedia.Wiki表示:

    This site definitely has all of the information and facts I wanted about this
    subject and didn’t know who to ask. https://Idpedia.wiki/index.php/Exploring_The_Best_Magazines_In_Canada:_A_Guide_For_Readers

  15. Click Here表示:

    Hi there! I know this is kinda off topic but I was
    wondering if you knew where I could find a
    captcha plugin for my comment form? I’m using the same blog platform as yours and I’m having trouble finding one?

    Thanks a lot!

  16. FrankGlora表示:

    USA India Pharm: online shopping pharmacy india – USA India Pharm

  17. dvikazpag表示:

    Además, es importante recordar que el juego de azar no debe ser visto de ninguna forma como una manera de generar ingresos, disfrute del juego y manténgalo como un pasatiempo entretenido. The FC Pro Open Regional Cups Playoffs will be played using the in-Game Ultimate Team mode in the 1v1 dedicated competitive mode. All matches will be one (1) single game. The winner of the match is the Competitor with the higher score at the end. If the game is at a tied state, extra time will be used, followed by the penalty shootout, if needed, to find an outright winner of the match. de Evoplay Competitors must have access to the Competitive game mode in-Game to participate in the EA SPORTS FC Pro Open Regional Qualifier. Competitors will have to navigate to the ‘Competitive’ tab within the Ultimate Team mode in-Game to invite or to receive an invite from their opponent.
    http://termispwebney1979.raidersfanteamshop.com/descripcion-aqui
    Efelec Energy pertenece a laAasociación sectorial de la Energía Solar Fotovoltaica en España Los jugadores deben realizar todas las apuestas después de que se liquide la última ronda de apuestas y antes del siguiente giro, pero no para la billetera. Esto significa que los jugadores pueden disfrutar de una experiencia de juego segura y justa con juegos fuertemente regulados y, como aprender a jugar ruleta en el casino electronica pero solo puede activarlo gastando dinero de antemano. En esta máquina tragamonedas no existen como tal bonificaciones adicionales, pues tu objetivo es elegir dónde pateará el jugador del equipo elegido en el punto de penalti. Luego de escoger a tu seleccionado favorito, comenzarán las apuestas y te enfrentarás en una tanda de penaltis con otras escuadras. Tendrás la oportunidad de elegir la cantidad de la apuesta que deseas realizar, y también podrás seleccionar dónde patearán tus jugadores, tratando de adivinar el lado correcto sin que el portero ataje tu cobro. Es bastante simple.

  18. Cazrfig表示:

    Где приобрести диплом по необходимой специальности?
    Мы изготавливаем дипломы любых профессий по приятным ценам. Важно, чтобы дипломы были доступны для большого количества граждан. Купить диплом о высшем образовании kupit-diplom24.com/kupit-diplom-vnesennij-v-reestr-9/

  19. Hello colleagues, pleasant paragraph and good arguments commented
    here, I am truly enjoying by these.

  20. CarltonUnith表示:

    https://usaindiapharm.shop/# indian pharmacies safe

  21. Waltonnix表示:

    world pharmacy india: USA India Pharm – top online pharmacy india

  22. Заинтересованы в качественной продукции?, посетите. Вы найдете у нас много интересного. Не пропустите шанс, ознакомиться с новинками. и будьте в курсе акций. Гарантия качества – это то, что мы гарантируем. Покупайте легко и быстро.
    штани мультикам купити штани мультикам купити .

  23. Few females have negative experiences with Cardarine just because it’s so side-effect-friendly.

    The only unfavorable might be those girls wanting more hardcore results – by which case they will use one thing like Anavar as an alternative or a
    more potent fat burner like Clenbuterol. Morning administration at all times works
    nicely, but some individuals swear by taking their daily dose briefly (about 15 minutes) before coaching
    or working. Experimenting with totally different instances of day for your dose will yield the most effective outcomes on your schedule however aim to take it on the same time each day
    every time attainable. Cardarine may be taken once day by day; it’s usually finest to take it in the morning or earlier
    than coaching. Some suppliers additionally sell Cardarine
    in powder and capsule forms (10mg tablets, for example).

    The wide number of SARMs makes it appealing
    to stack two or extra together with Cardarine to attain a more specific end result.
    Most advanced Cardarine customers will be on the stage the place stacking it with different potent compounds will be the solely option to
    take performance and outcomes to a different level.
    Since rising Cardarine’s dosage past 20mg or 25mg holds no notable benefits but only potential downsides, stacks just like the examples famous below
    are the best choice for all superior customers.
    Relying in your steroid expertise, using Deca at anywhere from 300mg to 600mg weekly mixed
    with 10-20mg daily of Cardarine goes to end in a strong bulking
    outcome with a 10-week cycle. PCT might be required because of Deca’s excessive testosterone suppression activity.

    Feminine runners who use Cardarine observe that, equally to men, the endurance and stamina modifications come on shortly and are vital.

    Also, since the early 1970s, many female athletes have started taking different virilizing steroids, similar to testosterone esters
    and nandrolone (Deca Durabolin). One possible purpose why such results grew to become apparent some 10 years after the athletes began taking Turinabol was as a
    end result of dosages had been gradually increased every year.
    Thus, German scientists’ goal was to synthesize a steroid that would replicate the
    anabolic (muscle-building) and strength-enhancing effects of Dianabol but without fluid achieve.

    It is formulated with ingredients like soy protein isolate,
    whey protein focus, BCAA, and ATP, which are all
    essential to building and sustaining muscles.
    On the opposite hand, Anavar is a synthetic steroid that may trigger important hurt to your physique over time.
    Most folks will begin to see outcomes from Anavar inside the first week or
    two of use. Nevertheless, it may take as a lot as four weeks
    for the total effects of the drug to be seen. The results
    will vary relying on the individual’s food regimen, exercise routine,
    and dosage.
    In my experience, this is the greatest way to use
    Anavar because we don’t need (or even want) to maintain constant levels of this liver-toxic steroid (no matter how mild) 24 hours a day.
    Oxandrolone was little doubt decided to be a light anabolic steroid
    method again then, which made it attainable to be tolerated by feminine and
    baby patients10. However, the acquisition of anabolic steroids is a prohibited activity that entails numerous
    further drawbacks. These embrace Anavar supplements being counterfeited,
    underdosed, or contaminated with dangerous substances (4).

    Factors that affect these results are the individual’s cycle, dose,
    genetics, diet, and training routines. Some customers have reported features of up
    to 10-15lbs of muscle mass and 7lbs of fats loss inside a 5- to 6-week cycle.
    Nonetheless, it’s essential to remember that particular person outcomes might vary.
    One essential side of managing hormonal steadiness is monitoring estrogen ranges.
    Though Anavar use may not cause a big enhance in estrogen, it’s nonetheless
    important to maintain it in examine as an excess can lead to negative effects corresponding to
    water retention and gynecomastia. Moreover, regulating
    cortisol levels is vital for stopping muscle breakdown and selling fats loss during PCT.

    For these new to Anavar, it’s important to know the fundamentals of an Anavar cycle.

    Cardarine is especially suited to feminine customers as a result of
    it lacks hormonal exercise. No virilization risk exists for girls who use Cardarine,
    however that doesn’t imply taking an extreme dose (females also need
    to contemplate the other potential risks involved with Cardarine).

    The uptake of Cardarine by athletes got the attention of WADA (World Anti-Doping Agency), and in 2009, it was added to the listing
    of prohibited substances. No AAS can immediately have you ever burning fat like Clenbuterol can, so if that’s your number 1 aim, then Clen will
    all the time be the choice over any steroids.
    Many of us will say no – and should you don’t like feeling the consequences of highly effective stimulants,
    Clen isn’t for you. The suggestion is that the dose
    is slowly increased over about two weeks, followed by a break after
    which a continuation of the cycle if you select to continue.

    Whereas Anavar has gentle pure testosterone suppression results, it not often fully suppresses and even suppresses at half the pure ranges.
    Hence, the decrease in SHBG is still extremely useful no matter your testosterone levels when using this steroid.
    But there is not a getting round the fact that Anavar remains to be a steroid.

    No steroid can truly be thought of a gentle substance when used at doses for bodybuilding;
    it’s just that Anavar is considered “pretty mild” compared to the really heavy
    stuff.
    Anavar has garnered a significant following amongst athletes, and a lot of have
    shared their success stories and optimistic experiences.
    Reading in regards to the achievements of others can encourage and inspire you on your own journey.
    Hearing in regards to the experiences of different Anavar customers can provide priceless insights and perspectives.

    Liver harm should not be discounted as a possible side effect of Anavar, particularly if
    excessive doses are administered for extended durations. Crazy Bulk’s
    formulas are supported by clinical research and are safe for men and women to make
    use of. Anavar will increase T3 by reducing TBG (thyroid-binding globulin) whereas simultaneously elevating TBP (thyroxine-binding
    prealbumin). If you suffer from hypogonadism and
    require testosterone for medicinal purposes, we recommend Olympus Men’s TRT program.
    Remember, the goal is to enhance your health and fitness,
    not compromise it. For example, if you are experiencing abdomen upset,
    you could need to take Anavar with food or at a unique time
    of day. If you are experiencing insomnia, you might want to keep away from taking Anavar before mattress.

    References:

    buysteroidsonline, sugarmummyarab.com,

  24. Phising表示:

    Pretty component of content. I simply stumbled upon your site and in accession capital to claim
    that I get in fact loved account your blog posts.
    Any way I will be subscribing to your augment and even I achievement you access constantly fast.

  25. worldcupPsync表示:

    Cool + for the post
    _________________
    cricket-2025

發佈留言

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