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,672,997 Responses

  1. escorts luton表示:

    A person essentially lend a hand to make significantly
    posts I’d state. That is the first time I frequented your web page and to this point?
    I amazed with the research you made to create this actual
    publish amazing. Wonderful job!

  2. Sis is hot! Indian sex with sister, not prohibited any longer.

  3. FrankGlora表示:

    UsaIndiaPharm: UsaIndiaPharm – india pharmacy

  4. worldcupPsync表示:

    thanks, interesting read
    _________________
    indian premier league 2025

  5. What’s up, after reading this remarkable piece of writing i am as well delighted to share my
    knowledge here with friends.

  6. giqatbxrk表示:

    Street Football Show Interfering with gameplay, including purposefully breaking a game station, interrupting the power supply, leaving a station before the conclusion of a match, refusing to play, and abuse of in-game pausing; Couples Games For Adults Para ser más específicos, esta semana será más de lo mismo con los mejores del mundo compitiendo por la Jarra de Clarete en el 149th Open Championship en Royal St. Pruebe nuestros casinos recomendados de Playson y no se arrepentirá, hay grandes ofertas de diferentes tragamonedas. Para poder garantizar que los clientes de todo el mundo y los casinos sigan teniendo demanda, por lo que como cliente puede obtener la mayor variación posible. El bono Hippo es un bono de pick em aburrido que otorga premios en efectivo, no dirías. Como resultado, a menudo se agregan automáticamente a la cuenta a bordo. En nuestra opinión, americana y europea. Lo bueno de Paysafecard es que su aplicación no se limita a los sitios de juego, una comisión federal de estudio sobre juegos de azar ha. Sin embargo, que incluyen tragamonedas.
    http://terlesspawde1981.iamarrows.com/https-amesol-org-mx
    Penalty Shoot Out 1win es un Juego basado en RNG (Generador de Números Aleatorios) donde tienes que golpear la pelota dentro de la portería. Si aciertas 5 veces, ganas y si no, la ronda empieza de nuevo. El juego es compatible con smartphones Android y iOS gracias al desarrollo en HTML5, por lo que también puedes jugar en la app gratuita. 1Win no tiene una aplicación real para iOS, pero puedes crear un acceso directo a la plataforma desde Safari. Esto te permitirá acceder a 1Win rápida y fácilmente desde la pantalla de inicio de tu teléfono. Además, de esta forma ahorrarás espacio libre en tu dispositivo. Estos son los pasos para descargar 1Win en tu dispositivo iOS: Los juegos de 1Win Argentina son LA opción ideal para los aficionados a los juegos de casino y azar. Al combinar perfectamente la estrategia con el azar, resulta en una experiencia emocionante y desafiante. 

  7. Waltonnix表示:

    USA India Pharm: UsaIndiaPharm – UsaIndiaPharm

  8. The Reasons Behind Why Online Casinos Remain Highly Preferred Worldwide

    Virtual gambling platforms have changed the gambling market, delivering a unique kind of accessibility and breadth that brick-and-mortar gambling houses struggle to rival. Over the past decade, millions of players internationally have embraced the excitement of virtual gambling in light of its always-open nature, captivating elements, and widening range of offerings.

    One of the biggest attractions of internet-based platforms is the vast selection of entertainment options on offer. Whether you are a fan of rolling classic slots, trying out plot-filled modern slot games, or exercising tactics in classic casino games like Baccarat, internet-based gambling sites boast countless choices. Numerous services also introduce interactive dealer games, allowing you to participate with professional croupiers and opponents, all while soaking in the realistic ambiance of a traditional gambling venue without leaving your home.

    If you’re new with the world of virtual casino play or seek to explore reputable operators, why not participate in our vibrant gaming forum? It’s a platform where fans post stories, guiding you to get the most out of your online casino experience. Join the community and see it here now: vavada casino.

    Beyond variety, virtual gambling platforms excel accessibility.

  9. Waltonnix表示:

    USA India Pharm: buy prescription drugs from india – top 10 online pharmacy in india

  10. Хотите найти что-то особенное?, наш сайт Camogear. Вы найдете у нас много интересного. Убедитесь сами, высшего качества. Станьте частью нашего сообщества. Гарантия качества – это то, к чему мы стремимся. в нашем онлайн-магазине.
    штани з наколінниками штани з наколінниками .

  11. Ищете уникальные товары?, интернет-магазин Camogear. Вы найдете у нас много интересного. Не упустите возможность, ознакомиться с новинками. Станьте частью нашего сообщества. Гарантия качества – это то, что мы гарантируем. в нашем интернет-магазине.
    купити форму мультикам https://camogear.com.ua/ .

  12. lhmtmfhlu表示:

    English dictionary and learning for Spanish speakers To add penalty shootout to a word list please sign up or log in. Discover the new Miniplay Chrome extension English dictionary and learning for Spanish speakers Immersive learning for 25 languages Los usuarios de Penalty shootout – Game le dio una calificación de 4 fuera de 5 estrellas. The middle part is the shootout itself. This is a beautifully designed 20-second long sequence that is as equally nerve-wracking as the real-life penalty kick. The scenes are designed by using motion capture technology with real-life football players and gatekeepers helping NSoft to create the game. In the exhilarating world of “football strike multiplayer soccer,” the penalty shootout game stands as the ultimate test of nerves and skill. A striker must face the intense pressure of a penalty kick, aiming to outwit the vigilant goalkeeper. The foot strike of the football champion can decide the fate of their team in the Football League, where penalty shootouts are both a science and an art.
    https://www.localstar.org/Leeesto
    Finalizada la instalación podrá ingresar a la app e ir a la sección del casino para jugar Penalty Shoot Out. En el caso de iOS puede ingresar desde la versión móvil diseñada para adaptarse a todas las pantallas desde el navegador. Gabriel Jesus (knee), Kai Havertz (hamstring), Takehiro Tomiyasu (knee), Gabriel Magalhaes (hamstring), and Riccardo Calafiori will miss the game for the Gunners due to injuries. Raheem Sterling will be banned for this game. Bukayo Saka is expected to be back in the playing XI. Moreover, Mikel Merino should be fit for this game as well, after suffering a cut to his head in the previous game. Let us take a look at the predicted lineup of Arsenal against Real Madrid. En este juego de Penalty Shoot Out slot tendrás posibilidades de ganar dinero real reales, ya que el RTP que ofrece equivale hasta un 96%, aún así la volatilidad del juego está presente, por lo tanto es posible ganar pero las derrotas también son parte del juego. Lo mejor que puedes hacer es aplicar una estrategia a largo plazo.

  13. Marital relationship and sharing of an Indian spouse– a controversial topic.

  14. Jarioryhj表示:

    Где купить диплом по нужной специальности?
    Мы предлагаем быстро заказать диплом, который выполнен на бланке ГОЗНАКа и заверен печатями, водяными знаками, подписями официальных лиц. Документ способен пройти любые проверки, даже при помощи специфических приборов. Решайте свои задачи быстро и просто с нашей компанией.
    Заказать диплом о высшем образовании kupit-diplom24.com/kupit-diplom-sssr-23/

  15. Потолки для вашего дома от natyazhnye-potolki-dnepr.biz.ua , где качество встречает стиль, добавьте шарм вашему пространству, решение, которое преобразит ваш дом.
    Премиум натяжные потолки в Днепре, профессиональный подход, которые создадут уют и гармонию, закажите прямо сейчас.
    Экономьте с умом с натяжными потолками, с качеством, проверенным временем, выберите лучшее для вашего дома, сделайте выбор в пользу качества.
    Натяжные потолки, созданные с любовью, потолки, которые вдохновляют, превратите мечты в реальность, измените пространство вокруг себя.
    Эстетика и функциональность натяжных потолков, отечественного производства, создайте свой идеальный интерьер, у нас широкий ассортимент.
    Почему стоит выбрать натяжные потолки?, для вашего комфорта, долговечность и надежность, позаботьтесь о своем жилье.
    Творческие идеи для натяжных потолков, где стиль и качество соединяются, обратите внимание на детали, наш опыт к вашим услугам.
    Натяжные потолки: легко и удобно, с нами легко и быстро, доступные решения для каждого, свой идеальный потолок в 3 шага.
    Качество натяжных потолков — наш приоритет, от natyazhnye-potolki-dnepr.biz.ua, мы знаем, как сделать ваш потолок идеальным, придайте своему интерьеру новое дыхание.
    Где купить натяжные потолки в Днепре?, у надежных поставщиков, где ваши мечты становятся реальностью, не упустите свой шанс.
    Натяжные потолки: быстро и стильно, с качеством, проверенным временем, нам доверяют тысячи клиентов, закажите свою консультацию.
    Натяжные потолки для каждого интерьера, где стиль встречается с практичностью, на любой вкус и бюджет, обратите внимание на наши предложения.
    Опытные специалисты по натяжным потолкам, от natyazhnye-potolki-dnepr.biz.ua, потолок, о котором вы всегда мечтали, присоединяйтесь к нам.
    Натяжные потолки для ваших идей, с заботой о каждом клиенте, всё для вашего комфорта и стиля, действуйте сейчас.
    Ваш потолок — ваша гордость, потолки для любого стиля, с равной страстью к вашему проекту, не откладывайте на завтра.
    Преимущества натяжных потолков в вашем интерьере, от надежных производителей, мы создаем счастье для ваших глаз, сделайте правильный выбор.
    натяжной потолок https://natyazhnye-potolki-dnepr.biz.ua/ .

  16. Dannyriz表示:

    аренда автомобиля спб на сутки аренда авто в спб для поездки

  17. Excellent material, yet it requires more antarvasna porn videos.

  18. DavidSooni表示:

    indian pharmacies safe buy prescription drugs from india buy prescription drugs from india

  19. Georgeunula表示:

    UsaIndiaPharm: reputable indian pharmacies – UsaIndiaPharm

  20. Dannyriz表示:

    сколько стоит аренда машины в спб аренда авто в спб без водителя посуточно

  21. Anavar is extra commonly used for chopping cycles due to its capacity to protect lean muscle mass while
    selling fat loss. Nevertheless, it can additionally be utilized in a bulking cycle to
    help enhance energy and endurance. Using Anavar during a steroid cycle is a extremely efficient technique of growing lean muscle mass.
    This sturdy anabolic steroid could aid in fats loss, muscle achieve, and
    efficiency enhancement.
    One of the primary ways Anavar aids in weight loss is thru its capacity to extend metabolic fee.
    The compound has been proven to boost the physique’s
    basal metabolic fee (BMR), which means that even at
    relaxation, the physique burns more energy.
    This elevated metabolic exercise can result in a extra environment friendly fat-burning
    course of, particularly when mixed with a calorie-controlled food plan and regular exercise.

    Anavar is a managed substance, so it’s only legally available via prescription. Many individuals buy it
    on the black market, but this comes with risks of counterfeit products.
    Common cardio or high-intensity interval coaching can be performed, which can help to lower blood pressure, while aiding in burning more fat.
    Nonetheless, ladies may take DHEA as post cycle therapy to speed up the restoration of their endogenous testosteroneproduction.
    Not to mention, this is an Anavar feature that is extremely useful for girls since they’re
    prone to storing extra belly fat as compared to men due to a better level of
    estrogen of their our bodies. Whey protein is absorbed
    shortly by the muscle and is required for fast muscle recovery.
    Whey protein is discovered in plenty of dietary supplements however when combined with different elements offers a faster absorption price helping your muscular
    tissues get well sooner. As you presumably can see
    the results are very spectacular and delivered good outcomes, best of all there
    aren’t any unwanted effects. “Secret Information to Anabolic Steroids” isn’t only a
    collection of words – it’s the blueprint for metamorphosing right into a more fascinating and attractive you.

    Dive deep into its contents to unravel the mysteries of
    various steroid types and their results. First – Anvarol is legal within the United States for everybody,
    Anavar can solely be bought by people with a prescription and is somehow
    illegal in the States.
    Nonetheless, this effect can be harmful if abused since rising anabolic exercise without first caring for vital organs just isn’t beneficial
    at all times because of its potential unwanted effects.
    It is a brand name for the artificial hormone oxandrolone, which is derived from
    DHT (dihydrotestosterone). Anavar was first created
    in 1964 and has been used for a variety of medical functions, together
    with the remedy of muscle losing ailments, osteoporosis, and Turner’s syndrome.

    It Is like photoshop on Instagram – you could be evaluating your self to folks on social media who go on about their routines and diets but not mentioning anything in regards to the
    drugs they’re taking.
    You can’t use a potent drug like Clenbuterol and not have a
    lot of adverse comments or complaints/concerns being shared.

    Feminine customers will typically be nicely aware of the downsides of Clen, and frequent feedback
    about jitters, anxiousness, and sleeping difficulty could be found.
    Many guys who regularly test their resting coronary heart price discover a important rise – sometimes 30 bpm or greater than traditional.
    This is Clen’s stimulant results kicking in and its
    thermogenesis and metabolism-raising exercise.
    Granted they received’t be as strong as anavar for ladies, however
    at least you won’t have permanent side effects.
    Superior users often enhance the oral dose up to 200mg every
    day, preserving in mind that these doses are unlikely to present
    the risks of liver toxicity. That is the case with
    almost all other oral steroids, where doses have to be restricted for that
    cause.
    Extra typically than not, ladies too experience a slowdown of their endogenous or pure testosterone ranges after they come off Anavar.
    This necessitates post-cycle remedy so as to revive
    their natural testosterone levels as quickly as potential.

    Having stated that, Anavar is prone to increase muscle mass and improve muscle definition as
    properly. I have personally used Anvarol for a few months at a time
    and it does assist increase vitality and get rid of body
    fat.
    Anvarol is a legit Anavar various that’s backed by scientific research that present it’s efficient in decreasing physique fat and preserving lean muscle mass.
    It can be created from all-natural elements which are safe for most people to make use of.
    Not Like different steroids, Primobolan doesn’t cause masculinizing unwanted aspect effects corresponding
    to excess body hair and deepening of the voice. This makes it a
    good selection for ladies who want to construct muscle without masculinizing unwanted effects.

    It additionally has the benefit of being relatively light on the liver,
    making it easier for girls to tolerate than different anabolic steroids.

    Anavar has gained significant interest, especially amongst female bodybuilders and athletes trying to build lean muscle while
    minimizing potential well being risks. Anavar promotes lean muscle mass progress in women, avoiding the bulbous appearance commonly acquired when taking other anabolic steroids.

    It operates through stimulated protein synthesis, supporting the buildup
    of the muscular tissues while keeping one in the
    line of being more female. Actually, this advantages girls who don’t like gaining massive muscular tissues
    but wish to define their muscle tissue.
    In conclusion, Anavar can supply significant benefits to female bodybuilders and athletes, even when utilized in transient cycles.
    These can vary from improved power and endurance to subtle enhancements in muscle development.
    When Anavar is used appropriately, there are typically no points, but
    it’s essential to recognize that potential dangers could arise solely with misuse or abuse.
    Understanding the unwanted effects is essential to making
    knowledgeable decisions about Anavar utilization.

    References:

    Steroids Testosterone

  22. Georgeunula表示:

    reputable indian pharmacies: UsaIndiaPharm – top 10 pharmacies in india

  23. URL表示:

    Hello, after reading this amazing post i am as well glad to share my
    knowledge here with mates.

  24. magnificent issues altogether, you just gained a brand new reader.
    What would you recommend about your submit that you simply made some days in the past?
    Any sure?

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

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