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,483 Responses

  1. Jasonzitte表示:

    Their online portal is user-friendly and intuitive.
    where can i get cheap cipro online
    Their international catalog is expansive.

  2. DonaldTyclE表示:

    equilibrado de ejes
    Equipos de ajuste: importante para el rendimiento estable y productivo de las maquinarias.

    En el entorno de la tecnologia moderna, donde la efectividad y la seguridad del aparato son de gran trascendencia, los sistemas de ajuste desempenan un rol fundamental. Estos dispositivos adaptados estan disenados para balancear y regular partes moviles, ya sea en maquinaria manufacturera, transportes de desplazamiento o incluso en dispositivos hogarenos.

    Para los expertos en soporte de dispositivos y los tecnicos, operar con equipos de ajuste es importante para asegurar el funcionamiento estable y fiable de cualquier sistema rotativo. Gracias a estas opciones tecnologicas avanzadas, es posible limitar considerablemente las movimientos, el ruido y la esfuerzo sobre los cojinetes, extendiendo la duracion de componentes valiosos.

    Tambien relevante es el tarea que tienen los dispositivos de equilibrado en la asistencia al usuario. El ayuda tecnico y el mantenimiento continuo empleando estos sistemas habilitan ofrecer prestaciones de gran calidad, aumentando la bienestar de los clientes.

    Para los duenos de proyectos, la inversion en estaciones de equilibrado y sensores puede ser fundamental para mejorar la eficiencia y rendimiento de sus aparatos. Esto es especialmente importante para los duenos de negocios que dirigen pequenas y medianas organizaciones, donde cada detalle cuenta.

    Por otro lado, los equipos de equilibrado tienen una amplia uso en el ambito de la seguridad y el supervision de estandar. Posibilitan identificar probables problemas, evitando mantenimientos onerosas y problemas a los equipos. Incluso, los datos extraidos de estos sistemas pueden utilizarse para mejorar metodos y incrementar la reconocimiento en plataformas de busqueda.

    Las campos de uso de los aparatos de equilibrado cubren diversas sectores, desde la elaboracion de ciclos hasta el supervision ambiental. No afecta si se refiere de importantes elaboraciones manufactureras o limitados establecimientos de uso personal, los dispositivos de equilibrado son necesarios para proteger un desempeno efectivo y sin presencia de paradas.

  3. Victorprima表示:

    I’m impressed with their commitment to customer care.
    will gabapentin show up urine drug test
    Their global network ensures the best medication prices.

  4. Victorprima表示:

    They offer the best prices on international brands.
    lisinopril 3
    Always a seamless experience, whether ordering domestically or internationally.

  5. Jasonzitte表示:

    Efficient service with a personal touch.
    gabapentin ct 100mg hartkapseln
    Their health awareness programs are game-changers.

  6. Victorprima表示:

    A global name with a reputation for excellence.
    where to buy lisinopril price
    Their global medical liaisons ensure top-quality care.

  7. Jasonzitte表示:

    Global reach with a touch of personal care.
    cytotec prices
    They stock quality medications from all over the world.

  8. I’m impressed, I have to admit. Rarely do I come across a blog that’s both educative and amusing, and without a doubt, you’ve
    hit the nail on the head. The problem is something not
    enough people are speaking intelligently about. I am very happy
    I found this in my search for something relating to this. https://Theterritorian.Com.au/index.php?page=user&action=pub_profile&id=1147078

  9. Jual Baja Terbaik , Supplier Sinar Baja , Jual Besi
    Baja Terlengkap , Jual Baja Terlengkap Kota Medan, Distributor Besi
    Kota Medan

  10. Hi, just wanted to tell you, I enjoyed this article. It was helpful.

    Keep on posting!

  11. Victorprima表示:

    The widest range of international brands under one roof.
    gabapentin used with hydrocodone
    Leading with integrity on the international front.

  12. Georgeappox表示:

    Hidden World War II tunnels to open to public
    адвокат

    In this week’s roundup of travel news: Denver’s weed church, zodiac predictions for the Year of the Snake, plus what promises to be London’s most ambitious – and deepest – new visitor attraction.

    Going underground
    Some 30 meters (98 feet) below central London lies a mile-long network of tunnels that is set to be the UK capital’s glitziest new tourist attraction, according to the company that’s secured planning approval for the $149 million transformation.

    The Kingsway Exchange Tunnels were built in the 1940s to shelter Londoners from the Blitz bombing campaign during World War II. That was the last time they were open to the general public. Their next wartime role was as the home of Britain’s top-secret Special Operations Executive, an offshoot of MI6 and the real-life inspiration for James Bond’s Q Branch.

    The new attraction will be a memorial to the Blitz, which Angus Murray, chief executive of the London Tunnels, told Reuters will be part museum, part exhibition and part entertainment space.

    The plan is to open to the public by late 2027 or early 2028. Read more here in our earlier story announcing the project.

    If you can’t wait until then to get down in the city’s bowels, London Transport Museum runs exclusive guided tours of its abandoned tube stations, including Down Street, a secret underground bunker that helped win World War II.
    Year of the Snake
    The first new moon of the lunar calendar fell on January 29, ushering in the Year of the Snake and the 15-day Spring Festival, a big annual highlight in China and for Chinese communities around the world.

    Here’s our guide to what it all means and, whether you’re a horse, goat, monkey, rooster or any other sign in the Chinese zodiac, here’s what the stars say are your predictions for the year ahead.

    Food is, of course, a key part of the celebrations. One of the most fun elements is the “prosperity toss,” kind of like a food fight with chopsticks but seasoned with auspicious blessings for the year ahead.

    For the culinarily adventurous, 2025 is a good time to visit Hong Kong and see how restaurants serve snake. Delights include snake balls and snake soup – and be sure to leave room for the penis wine. Watch here.

  13. bandar slot表示:

    Helpful information. Lucky me I found your web site by accident, and I am stunned why this coincidence didn’t came about earlier!
    I bookmarked it.

  14. DonaldTyclE表示:

    Monitoreo de condicion
    Aparatos de calibración: fundamental para el funcionamiento uniforme y óptimo de las máquinas.

    En el ámbito de la ciencia avanzada, donde la efectividad y la estabilidad del sistema son de máxima trascendencia, los sistemas de balanceo cumplen un tarea crucial. Estos aparatos dedicados están creados para ajustar y regular elementos dinámicas, ya sea en equipamiento de fábrica, automóviles de transporte o incluso en aparatos caseros.

    Para los especialistas en mantenimiento de aparatos y los técnicos, operar con equipos de equilibrado es crucial para garantizar el desempeño fluido y fiable de cualquier sistema giratorio. Gracias a estas opciones tecnológicas avanzadas, es posible minimizar significativamente las oscilaciones, el zumbido y la carga sobre los cojinetes, mejorando la tiempo de servicio de piezas costosos.

    Asimismo trascendental es el función que tienen los aparatos de calibración en la soporte al usuario. El soporte experto y el soporte constante utilizando estos sistemas permiten dar servicios de gran calidad, elevando la contento de los usuarios.

    Para los dueños de empresas, la aporte en estaciones de equilibrado y detectores puede ser esencial para aumentar la rendimiento y productividad de sus sistemas. Esto es particularmente relevante para los emprendedores que gestionan reducidas y pequeñas emprendimientos, donde cada aspecto es relevante.

    También, los equipos de calibración tienen una gran uso en el campo de la protección y el control de nivel. Habilitan encontrar probables problemas, reduciendo mantenimientos caras y problemas a los dispositivos. También, los indicadores recopilados de estos aparatos pueden usarse para perfeccionar procedimientos y potenciar la visibilidad en motores de búsqueda.

    Las zonas de aplicación de los aparatos de balanceo cubren numerosas áreas, desde la fabricación de transporte personal hasta el seguimiento ecológico. No importa si se habla de enormes producciones manufactureras o pequeños talleres hogareños, los aparatos de equilibrado son indispensables para asegurar un operación efectivo y sin presencia de paradas.

  15. PinUp - w6表示:

    Pin Up Casino в Казахстане – это одно из самых популярных мест для ценителей азарта. Здесь созданы все условия для выигрышей для развлечений и крупных выигрышей. Если вы любите играть в хороших казино, то Pin Up Казино – это именно то, что вам нужно.

    Преимущества Pin Up Казино Онлайн

    Большой ассортимент игр. В Pin Up Казино доступно более 2000 видеослотов, игр с живыми крупье и автоматов. В линейке игр представлены такие известные разработчики, как Evolution Gaming и другие. Это значит, что вы получите отличное качество игры, доступные на всех устройствах.

    Выгодные бонусы и акции. Новички сразу получают увеличенные стартовые бонусы, которые дадут хорошие шансы на выигрыш. Кроме того, действуют постоянные акции, ежедневные розыгрыши и фриспины для постоянных пользователей, что делает игру ещё более захватывающей и выгодной.

    Наш сайт: https://bk.kz/news/?month=03&year=2010&PAGEN_2=7

    Надёжность и безопасность. Pin Up Казино использует современные технологии для защиты данных и транзакций, чтобы гарантировать защиту данных. Казино работает по лицензии гарантирует честные выплаты и честные и быстрые выплаты.

    Полная мобильная совместимость. Наше казино оптимизировано для смартфонов, что даёт возможность играть в любые игры в любом удобном месте. Можно скачать приложение для смартфона или просто зайти на сайт через браузер смартфона.

    Круглосуточная поддержка. В любом вопросе, служба помощи всегда на связи. Вы можете связаться с операторами через чат и email, и операторы ответят в кратчайшие сроки на удобном языке.

  16. Jasonzitte表示:

    They offer great recommendations on vitamins.
    where can i get cheap clomid without prescription
    Their worldwide outreach programs are commendable.

  17. DonDonrob表示:

    darknet markets links https://github.com/nexusdarkneturlwrf4t/nexusdarkneturl – dark web market urls

  18. Sazrzrj表示:

    Привет, друзья!
    Приобретение диплома через проверенную и надежную фирму дарит ряд преимуществ. Это решение помогает сэкономить как дорогое время, так и существенные финансовые средства. Тем не менее, плюсов гораздо больше.Мы предлагаем дипломы психологов, юристов, экономистов и прочих профессий. Дипломы производятся на подлинных бланках. Доступная стоимость по сравнению с огромными тратами на обучение и проживание в чужом городе. Приобретение диплома ВУЗа является целесообразным шагом.
    Быстро заказать диплом о высшем образовании: flashboot.ru/profile/diplomygroup

  19. The Complete Guide To Buffy Macaw Bird For Sale buy macaw Parrot

  20. BALL7M表示:

    Its like you learn my mind! You seem to grasp so much about this, such as you wrote the ebook in it
    or something. I think that you just could do with some p.c.
    to pressure the message house a bit, but other than that, that is great
    blog. A great read. I’ll certainly be back.

  21. Ощутите себя капитаном, отправившись в незабываемое плавание!

    К вашим услугам
    прокат теплоход казань
    для захватывающих приключений.

    С нами вы сможете:
    • Насладиться живописными пейзажами с борта различных судов.

    • Отпраздновать знаменательное событие в необычной обстановке.

    • Провести незабываемый вечер в
    романтической атмосфере.
    • Собраться с близкими друзьями для
    веселого время провождения.

    Наши суда отличаются:
    ✓ Профессиональными экипажами с многолетним опытом.

    ✓ Повышенным уровнем комфорта для пассажиров.

    ✓ Гарантией безопасности на протяжении всей поездки.

    ✓ Привлекательным внешним видом
    и стильным дизайном.
    Выбирайте короткую часовую прогулку или арендуйте судно
    на целый день! Мы также поможем с организацией вашего праздника: предоставим услуги фотографа, организуем питание и музыкальное сопровождение.

    Подарите себе и своим близким незабываемые моменты!

    Забронируйте вашу водную феерию уже сегодня!

  22. Cricket Nets Dubai supplies the ideal training atmosphere for cricketers of all skill levels looking
    to refine their video game. Whether you are an amateur gamer or an expert cricketer,
    practicing in top notch cricket internet assists boost batting, bowling, and fielding strategies.

    Dubai has become a popular center for cricket training, supplying several of the best centers with innovative devices,
    professional training, and well-kept pitches. The enhancing popularity of cricket in Dubai has actually brought about the development of first-rate
    technique nets that give an organized and regulated
    environment for gamers to enhance their skills. Indoor cricket internet in Dubai use year-round
    training chances, making them ideal for gamers who want
    to train despite the climate condition. These centers offer a secure
    and enclosed environment that enables gamers to focus on their game with no disturbances.
    Geared up with professional-grade netting, artificial turf, and automated bowling makers, indoor cricket webs assist gamers service their batting stance, shot option, and bowling precision.
    Training in a climate-controlled setting guarantees that cricketers can practice in a consistent and continuous
    fashion. The encased arrangement likewise boosts muscle memory, reaction time, and general precision, which are important for affordable cricket.
    Outdoor cricket webs in Dubai offer a more match-like
    experience, permitting gamers to educate on natural grass arches in open fields.

    These method internet are created for both newbies
    and progressed cricketers that wish to establish their abilities in sensible playing conditions.
    The properly maintained pitches, protective netting,
    and progressed training devices make certain that players get the very best feasible method experience.
    Practicing in outside webs aids players improve their versatility, footwork, and fielding reflexes,
    which are essential for match performance. Exterior cricket internet additionally provide bowlers the possibility
    to deal with their line and size while mimicing real-game problems.
    Cricket nets in Dubai deal with individual players, teams, and clubs trying to find structured training programs.
    The existence of expert training staff guarantees that gamers receive personalized training
    customized to their skill degree. Numerous cricket
    net facilities in Dubai supply mentoring services from knowledgeable professionals, assisting gamers improve
    their batting technique, bowling precision, and fielding coordination. Whether concentrating on fast bowling,
    spin strategies, power striking, or wicket-keeping
    drills, cricket webs provide a devoted space for fine-tuning all aspects of the video game.
    Regular method in cricket internet helps players develop confidence, improve uniformity,
    and obtain an one-upmanship. Scheduling cricket webs in Dubai
    is easy, with several facilities offering adaptable
    rental choices for people and groups. These cricket internet can be
    scheduled for personal practice, team training, or event preparation. The accessibility of well-kept practice areas, advanced training techniques,
    and performance analysis tools makes Dubai among the leading locations for cricket training.

    Practicing in top notch cricket nets ensures that gamers develop their abilities in a professional setup.
    The organized training atmosphere at these cricket
    internet cultivates team effort, self-control, and
    sportsmanship, making them a vital part of any kind of cricketer’& rsquo; s trip.
    The centers at cricket internet in Dubai include first-class training devices such as high-speed bowling
    machines, fielding method zones, and batting cages.
    These attributes supply gamers with the possibility to improve their
    strategy and perfect their game under the advice of professional trains.
    Cricket internet assist gamers work on different elements of the video game, consisting of batting drills, bowling accuracy, and fielding reflexes.
    The visibility of well-maintained equipment and expert
    coaching ensures that players can concentrate on their training without any
    disturbances. Cricket webs in Dubai provide a secure and regulated atmosphere
    that encourages players to press their limits and improve their total performance.

    Dubai is home to a vivid cricketing area, with players from various histories coming together to train and compete.
    The city’& rsquo; s world-class cricket training infrastructure has actually drawn in gamers
    from around the globe that seek top notch mentoring and method centers.
    Cricket internet in Dubai offer an organized technique to ability advancement, aiding players of all
    degrees fine-tune their strategies and get important suit experience.

    The well-maintained pitches and specialist coaching
    team guarantee that every player obtains the most effective feasible training.

    Whether getting ready for an affordable match or merely wanting to boost
    cricketing skills, the cricket webs in Dubai provide an unequaled training
    experience. The structured training sessions at cricket webs
    in Dubai assistance gamers create vital abilities such as maneuvering, shot option, and video game
    awareness. The presence of specialist trainers guarantees that players obtain continual comments, enabling them to identify weaknesses and deal with improvements.
    The controlled environment of cricket internet aids
    gamers preserve emphasis and deal with fine-tuning their skills.

    With the schedule of both interior and outdoor technique areas,
    gamers can train under different conditions to enhance their versatility and suit readiness.
    The presence of bowling machines, training devices,
    and fielding drills guarantees that players obtain extensive training that covers all facets
    of cricket. Cricket nets in Dubai are optimal for players
    wanting to improve their performance in an organized and expert environment.

    The accessibility of high-grade devices, experienced coaching team,
    and properly maintained centers makes these training locations the favored
    option for numerous cricketers. Exercising in cricket training grounds Dubai internet aids players build self-confidence, enhance strategy, and create suit
    methods. The competitive training atmosphere fosters a solid cricketing state of mind, motivating gamers to constantly improve and take their video game to the following degree.
    With numerous training centers across Dubai, players have accessibility to some of the best cricket internet offered.

    The cricketing culture in Dubai continues to expand,
    with more players signing up with expert training
    programs to improve their skills. Cricket webs give the structure for
    enhancing batting, bowling, and fielding methods, enabling gamers
    to maximize their potential. The mix of organized training,
    high-quality facilities, and progressed training devices makes sure that gamers obtain top-tier training.
    Cricket internet in Dubai help players refine their video game, establish match methods, and gain self-confidence in their capabilities.

    Training in fully equipped practice internet offers an opportunity to construct uniformity and plan for high-level competitions.
    Cricket nets in Dubai provide an expert and organized training atmosphere where players can work on their
    skills under expert guidance. The accessibility of high-quality pitches, advanced training
    tools, and experienced coaching staff ensures that every
    cricketer gets the very best feasible training experience.
    The controlled atmosphere allows players to concentrate on ability advancement and suit prep work.

    Whether training for a tournament or merely seeking to boost their video game, cricket nets provide the excellent setting for devoted method.
    Exercising regularly in a structured environment aids players create uniformity, fine-tune strategies, and enhance
    overall efficiency in cricket.

  23. DonaldTyclE表示:

    Diagnostico de equipos
    Sistemas de calibración: esencial para el operación fluido y óptimo de las equipos.

    En el mundo de la avances moderna, donde la efectividad y la seguridad del dispositivo son de gran significancia, los aparatos de equilibrado tienen un tarea vital. Estos equipos adaptados están concebidos para balancear y fijar componentes dinámicas, ya sea en maquinaria productiva, transportes de movilidad o incluso en dispositivos de uso diario.

    Para los técnicos en conservación de sistemas y los técnicos, utilizar con equipos de balanceo es importante para proteger el funcionamiento suave y estable de cualquier dispositivo móvil. Gracias a estas herramientas modernas innovadoras, es posible disminuir notablemente las sacudidas, el zumbido y la presión sobre los rodamientos, mejorando la vida útil de elementos importantes.

    También importante es el tarea que juegan los equipos de ajuste en la servicio al cliente. El asistencia técnico y el reparación continuo usando estos aparatos permiten proporcionar asistencias de gran calidad, aumentando la agrado de los compradores.

    Para los propietarios de emprendimientos, la financiamiento en equipos de ajuste y dispositivos puede ser importante para mejorar la productividad y productividad de sus aparatos. Esto es especialmente relevante para los dueños de negocios que dirigen modestas y pequeñas empresas, donde cada punto importa.

    Asimismo, los aparatos de balanceo tienen una extensa implementación en el sector de la fiabilidad y el monitoreo de calidad. Habilitan encontrar potenciales fallos, evitando mantenimientos costosas y daños a los dispositivos. También, los información obtenidos de estos aparatos pueden usarse para perfeccionar procesos y mejorar la exposición en buscadores de exploración.

    Las campos de aplicación de los equipos de balanceo comprenden variadas ramas, desde la producción de bicicletas hasta el control del medio ambiente. No influye si se habla de importantes elaboraciones manufactureras o reducidos talleres domésticos, los dispositivos de ajuste son fundamentales para garantizar un funcionamiento productivo y sin riesgo de fallos.

  24. DonaldTyclE表示:

    equilibrado de turbinas
    Equipos de ajuste: esencial para el rendimiento fluido y eficiente de las dispositivos.

    En el ámbito de la avances moderna, donde la efectividad y la seguridad del dispositivo son de suma relevancia, los aparatos de calibración juegan un rol crucial. Estos dispositivos adaptados están creados para ajustar y estabilizar piezas rotativas, ya sea en maquinaria de fábrica, transportes de traslado o incluso en electrodomésticos caseros.

    Para los especialistas en soporte de dispositivos y los técnicos, manejar con dispositivos de balanceo es importante para garantizar el funcionamiento uniforme y seguro de cualquier dispositivo dinámico. Gracias a estas soluciones tecnológicas innovadoras, es posible minimizar sustancialmente las movimientos, el sonido y la esfuerzo sobre los rodamientos, prolongando la duración de piezas costosos.

    También significativo es el tarea que cumplen los equipos de balanceo en la servicio al cliente. El ayuda técnico y el mantenimiento continuo aplicando estos sistemas habilitan dar soluciones de alta estándar, elevando la bienestar de los compradores.

    Para los propietarios de negocios, la contribución en estaciones de equilibrado y sensores puede ser clave para incrementar la productividad y rendimiento de sus dispositivos. Esto es especialmente importante para los emprendedores que gestionan pequeñas y intermedias negocios, donde cada punto cuenta.

    Asimismo, los aparatos de equilibrado tienen una vasta implementación en el campo de la fiabilidad y el supervisión de calidad. Permiten localizar posibles defectos, impidiendo reparaciones caras y problemas a los aparatos. Incluso, los resultados generados de estos dispositivos pueden aplicarse para maximizar procedimientos y potenciar la reconocimiento en motores de exploración.

    Las zonas de uso de los dispositivos de calibración comprenden variadas sectores, desde la manufactura de vehículos de dos ruedas hasta el seguimiento ambiental. No afecta si se refiere de enormes producciones de fábrica o modestos talleres hogareños, los equipos de balanceo son necesarios para proteger un operación productivo y sin riesgo de detenciones.

  25. Victorprima表示:

    They consistently go above and beyond for their customers.
    cost of generic lisinopril price
    Their staff is always eager to help and assist.

  26. What Is Buy Pallets UK And How To Use It Pallet buying​

  27. Jasonzitte表示:

    Their global health resources are unmatched.
    buy cipro without dr prescription
    This international pharmacy offers top-tier service globally.

  28. When I originally left a comment I seem to have clicked
    on the -Notify me when new comments are added- checkbox and now whenever a comment is added I receive four emails with the same comment.
    Perhaps there is a way you are able to remove me
    from that service? Thank you!

發佈留言

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