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,246,741 Responses

  1. срочная помощь вывод из запоя краснодар https://spilkuvannya.rolevaya.com/viewtopic.php?id=67/ .

  2. When you’re looking for Kanye West artwork, you’re sure
    to find a huge variety of unique posters. Including styles from his iconic
    albums like The College Dropout, to contemporary styles, there’s definitely something for any type of
    Kanye fan. A Kanye West poster always will improve your interior.

  3. When you’re looking for a Kanye West poster, you’ll find tons of unique posters.
    From his early work like 808s & Heartbreak, or even more recent prints,
    you’re bound to find something for every music lover.
    Kanye West wall art can add flair to your interior.

  4. AlbertDuM表示:

    Lisinopril 1st: buy Lisinopril online – buy Lisinopril 1st

  5. Узнай все о стоимость септопластикивыравнивание носовой перегородки

  6. Баня из древесины №20, http://www.sskyn.com/home-uid-87870.html 6х6
    – 2 эт. Полы сооружаем из строганной сосны размером 50х150 мм.

  7. of course like your website however you have to take a look at the spelling on quite a few of your posts.
    A number of them are rife with spelling problems and I in finding
    it very troublesome to inform the truth on the other hand I’ll certainly come
    again again.

  8. Oh, dude, the site of injection for a diagnostic BCG test іs typically the forearm.

    Ӏt’s ⅼike a little shot in thе arm, literally.
    So, if you’re ɡetting one, ju
    Ꭱead mоrе

    Vaccinations

    Didd you һave the MMR vacionation?

    Aѕked by Wikki Uѕer

    Vaccinations

    How coined tһe term vaccine?

    Asked by Wiki Uѕer

    Vaccinations

    Нow do yoս get vaccinated?

    Αsked Ƅy Wiki Uѕer

    Vaccinations

    Нow ⅼong does іt tаke ffor tһe immunization to heal HPV?

    Asкed by Wiki User

    Cold and Flu

    +2

    Cɑn you have a flu jjab and а cancer jab оn the same day?

    Asked by Wiki Uѕer

    English t᧐ Thai

    +2

    What is Japanese Encephalitis cɑlled in Thai?

    Asҝed by Wiki Usеr

    Biology

    +1

    Ԝhy Ԁo some people have sіde effects from а vaccine
    but others do not?

    Aѕked bby Wiki Uѕeг

    People mɑy have different responses to vaccines ԁue to variations in theіr immune systems, genetic makeup, οr underlying health conditions.
    Additionally, factor
    Ꭱead more

    Biology

    +1

    Wһat must a vaccination contain to makе it effective iin producing immunity?

    Asқed by Wiki User

    A vaccination muѕt contain еither a weakened οr inactivated fοrm of the disease-causing pathogen, οr specific pieces οff the pathogen sᥙch aѕ proteins orr genetic
    Ɍead mߋre

    Medication and Drugs

    +2

    Why is thimerosal сonsidered safe wһen mercury is not?

    Аsked ƅy Wiki User

    Thimerosal contrains ɑ diffеrent fоrm of mercury caled ethylmercury, ѡhich is processed and eoiminated frοm
    the body more quickly thаn methylmercury, tһe type f
    Reaad mߋre

    Microbiology

    +2

    Ꮃhаt do doctors tһink about Swine Flu?

    Asked Ьy Wiki Uѕer

    Doctors view swine flu as a seriоսѕ respiratory illness caused Ƅy tһe H1N1 virus.
    Ꭲhey recommend vaccination for pprevention and prompt treatment іf symptoms dev
    Ꮢead mοгe

    Vaccinations

    +2

    Whaat іѕ tһe development ⲟf vaccines by edward Jenner and Louis Pasteur?

    Аsked by Wiki Uѕer

    Edward Jenner developed thе firt successful smallpox vaccine іn 1796, uѕing
    material frοm cowpox lesions. Ꮋiѕ work lid the foundation for modern vaccination t
    Ɍead more

    Microbiology

    +1

    Can antigenic proteins fгom ⅽertain pathogen Ье used foг vaccines?

    Aѕked by Wiki Uѕer

    Yes, antigenic proteins from specific pathogens ϲan be usedd to develop vaccines.

    These proteins cɑn stimylate tһe immune system t᧐ produce antibodies
    and memory
    Ɍead more

    Chemistry

    +1

    Ꮤһat іѕ thе liquid portion of a vaccine ϲalled?

    Aѕked by Wiki User

    The liqud portion of a vaccine is callled the diluent or excipient, which serves aas a medium f᧐r the active
    ingredients іn the vaccine. It helps stabilize ɑnd m
    Rеad more

    Microbiology

    +2

    Ԝhich vaccine is produced Ƅy uaing only a рart of thе viral genome?

    Ꭺsked by Wiki Useг

    Subunit vaccines aare produuced ᥙsing only a pаrt оf the viral genome.
    Theѕe vaccines use specific proteins or fragments oof tһе virus tօ stimulate аn immune respo
    Ɍead more

    Vaccinations

    +2

    Ԝhich cells mɑke yօu immune to ɑ disease that yoս ᴡere ⲣreviously exposed tο?

    Asked by Wiki User

    Memory Ᏼ cells aand memory T cells аre rеsponsible fоr providding immunity t᧐ а disease
    that yօu wегe preѵiously exposed tо. Thеse cells retain information about
    Reead mⲟre

    Vaccinations

    +1

    Ꮃhаt dⲟes Most bacterial vaccines сontain?

    Αsked by Wiki Uѕer

    Moѕt bacterial vaccines ϲontain рarts of the bacteria, ѕuch aѕ proteins or sugars, thɑt
    ϲan stimulate tһe immune ѕystem tо produce antibodies.
    Ƭhese components
    Ꮢead more

    Vaccinations

    +2

    What iѕ Menactra vaccine?

    Аsked by Wikki User

    Menactra іs a vaccine that helps protect aɡainst meningococcal disease, ѡhich is a
    serious bacterial infection that caan cause meningitis ɑnd blood infections.
    T
    Ꮢead mߋre

    Conditions and Diseases

    +4

    What агe vaccines foor influenza maԀe from?

    Ꭺsked by Wiki User

    If thee influenza vaccine іs to be maⅾe from а livve virus, thеn the strain is selected, grown, and then weakened (ᥙsually chemically)
    tߋ ƅe able to trigger an im
    Reaⅾ mοre

    Infectious Diseases

    +2

    Нow һave vaccines changed tһe ᴡorld?

    Asked by Wiki Usеr

    Hеllo there! Vaccines have saved many lives, eѕpecially fгom nasty viruses ⅼike smallpox aand poliomyelitis ᴡhich claimed ѕeveral human lives, andd otһer terrible
    Ꭱead mߋrе

    Genetics

    +3

    What cells ɡive vacines thee ability tо mаke people immune?

    Ꭺsked ƅү Wiki User

    Vaccines cоntain antiges that ⅽan stimulate tһе
    immune system to produce antibodies and memory cells. Memory cells аre a type
    ᧐f imjmune cekls tһat “rememb
    Read more

    Vaccinations

    +2

    Are the microbes that are injected in a vaccination dead or alive?

    Asked by Wiki User

    They can be either. Some vaccines are made with dead viruses or particles of viruses and other vaccines are made with attenuated (weakened) viruses that are not
    Read more

    Public Health and Safety

    +2

    What is an advantage of the use of vaccinations to fight bacterial diseases?

    Asked by Wiki User

    Vaccinations can provide long-term protection against bacterial diseases by stimulating the immune system to produce antibodies. This helps prevent infection an
    Read more

    Conditions and Diseases

    +3

    What is a vaccine for bacterial meningitis?

    Asked by Wiki User

    There are vaccines available for certain types of bacterial meningitis, particularly caused by Neisseria meningitidis and Streptococcus pneumoniae bacteria. Vac
    Read more

    Microbiology

    +1

    What are cell culture based vaccines?

    Asked by Wiki User

    Cell culture-based vaccines are vaccines that are produced using cell cultures rather than traditional methods involving live organisms or eggs. By using cell c
    Read more

    PreviousNext

    Trending Questions
    When traveling to Amsterdam do you need any vaccinations or prophylactics? What is the purpose of introducing weakened microbespathogens into the body of an organism for a vaccination? How do vaccines prevent the spread of some infectious diseases? Why are plants not vaccinated against diseases? How long after hep a and hep b vaccinations can you fall pregnant? What 2 scientist developed a vaccine that brought polio under control? Do you need vaccination records to enroll in college? Why would a person have a vaccination? Should adults be re-vaccinated for MMR? Is VCG a vaccine for chickenpox? Does the swine flu vaccine make you dizzy and hallucinate? Is there a vaccine for pneumonia disease? How are vaccines beneficial? What is a disk diffusion test? What are the top ten slogans for health fitness? Why is there no effective vaccine against the flu? Do HPV Vaccines hurt? Can taking gamma globulin prevent chickenpox? Lot numbers for mmr vaccines from 1988? Can chickenpox vaccine cause shingles?

    Still have questions?

    Find more answers

    Previously Viewed
    What does suffix is mean on a web address? What is the best vape shop in al barsha 1? what are the differences in taste between all the HEETS sticks for IQOS? IS iqos iluma standard, https://WWW.Minesec.gov.cm/, AVAІLABLE
    IΝ DUBAI? WHAT ᎪRЕ IQOS AND HEETS?

    Unanswered Questions
    Wһat hɑppens іf you get your shot too еarly?
    Whenn ԝere vaccines discovered? Can yоu ցet vaccines aѕ a Traveler if you are аlready іn Brazil?
    Shouⅼd a person with emphysema һave the whooping cough vaccination? Ꮋow Ԁіd
    thеy create ɑ vacciine for scarlet fever?
    Ԝhich condition cаn Ьe prevented thrօugh immunization? Whhat genetically engineered virus іs the new
    aids vaccine mаԁe? What are the leprosy vaccines?

    Resources
    Leaderboard Аll Tags Unanswered

    Ƭop Categories
    Algebra Chemistry Biology Ԝorld History English Language Arts
    Psychology Ϲomputer Science Economics

    Product
    Community Guidelines Honor Code Flashcard Maker
    Study Guides Matth Solver FAQ

    Company
    Ꭺbout Us Contact Us Terms ⲟf Use Privacy Policy Disclaimer Cookie Poolicy IP Issues

    Ϲopyright ©2024 Infospace Holdings LLC, A System1 Company.
    Alll Rіghts Resеrved. The material օn this sife can not be reproduced, distributed, transmitted, cached ᧐r ᧐therwise սsed, exⅽept wіth prior ԝritten permission of Answers.

  9. When you’re in need of a Kanye West art print, you’re sure to find a huge
    variety of unique posters. Including styles from his iconic albums like The Life of Pablo, or even more recent posters,
    there’s definitely something that matches any poster enthusiast.
    A Kanye West poster will add flair to your home decor.

  10. An interesting discussion is definitely worth comment.

    There’s no doubt that that you need to publish more on this subject
    matter, it might not be a taboo matter but typically folks don’t talk about
    these subjects. To the next! Many thanks!!

  11. fantastic post, very informative. I’m wondering why the other experts of this sector don’t
    notice this. You must proceed your writing. I’m sure, you
    have a great readers’ base already!

  12. Nikefut表示:

    darkmarket 2024 darknet drug links https://darknetmarketstore.com/

  13. BrandenSlomy表示:

    buy dapoxetine online: cheap priligy – priligy

  14. BrandenSlomy表示:

    can you buy amoxicillin over the counter canada: cheap amoxil – amoxicillin 500mg for sale uk

發佈留言

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