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...

780,466 Responses

  1. GeorgeLierm表示:

    Fences look after the needs of a variety of purposes, from providing safety and sequestration to enhancing the aesthetics of a property. In what way, like any nature, fences require conservation, periodic repairs, and every now unvaried substitution to assure they continue to fulfill their intended functions. In this article, we’ll delve into the specific services offered about professional restrict companies, including adjust, institution, and replacement.

    Non-aligned Patch up Services:
    Over time, fences can suffer damage appropriate to unwell exposure, aging, or accidental damage. Unrefined issues cover warped or rotted wood, leaning posts, crushed panels, let go tools, and rusted metal components. Master hold at bay set right services lecture these issues speedily to resuscitate the rampart’s structural virtue and appearance. Skilled technicians assess the expense, recommend acceptable repairs, and efficiently gain over the necessary work, whether it involves replacing damaged sections, reinforcing rickety spots, or fixing hardware. Close to addressing issues at, uncommitted repair services serve prolong the lifespan of the fence and prevent more national damage.
    enclose replacement

    Vacillate Installation Services:
    Whether you’re installing a fresh fence for asylum, retirement, or aesthetic reasons, official wall installation services ensure a hassle-free activity from start to finish. These services typically on with a consultation to discuss the patient’s needs, preferences, and property specifications. Based on this gen, experts advise suitable enclosure materials, styles, and designs that completion the land’s architecture and tourney the desired functionality. Professional installers feel all aspects of the induction, from milieu preparation and delivery setting to panel or observer arrangement and unchangeable adjustments. During entrusting the area to experienced professionals, estate owners can ahead to a durable, fittingly installed fence that enhances check lure and land value.

    Fence Replacement Services:
    When a neutral reaches the d‚nouement of its lifespan or sustains irreparable hurt, replacement may be the most applied solution. Fence replacement services concern removing the existing unaligned and installing a new in unison tailored to the customer’s preferences and property requirements. Professional cavil companies bid a wide distribute of fencing materials, including wood, vinyl, aluminum, chain-link, and composite options, allowing property owners to choose the most applicable choice based on durability, maintenance requirements, and budget. With punctilious prominence to in depth and importance craftsmanship, uncommitted replacement services ensure a seamless conversion to a recent, principled unbiased that meets the worth’s needs and enhances its appeal.

    Conclusion:
    From repairing adolescent damages to installing new fences and replacing worn-out structures, licensed vacillating services play a crucial situation in maintaining the functionality, appearance, and value of residential and commercial properties. By partnering with knowing professionals, property owners can take advantage of peacefulness of positive private that their fencing needs are in apt hands, ensuring long-lasting, attracting fences that act as their intended purposes effectively.

  2. I was recommended tthis website by my cousin. I’m now not certain whether orr not this post is written byy means of
    him as nobody else realize such certain about my
    trouble. You aree wonderful! Thank you!

    my blog slot gacor hari ini

  3. Hello, just wanted to mention, I loved this blog post.
    It was helpful. Keep on posting!

  4. kontol kuda表示:

    I visited multiple web pages but the audio quality for audio songs current at this site
    is really fabulous.

  5. WilliamSoorp表示:

    https://edwithoutdoctorprescription.pro/# viagra without a doctor prescription

  6. I like looking through an article that can make men and
    women think. Also, thank you for permitting me to comment!

  7. Adventure表示:

    My brother recommended I would possibly like this
    blog. He was totally right. This post actually made my day.

    You can not consider simply how a lot time I had spent
    for this info! Thanks!

  8. WilliamSoorp表示:

    http://certifiedpharmacymexico.pro/# best online pharmacies in mexico

  9. spam表示:

    Yes! Finally something about spam.

  10. I must thank you for the efforts you’ve put in writing this site.
    I really hope to see the same high-grade blog posts by you in the future as
    well. In truth, your creative writing abilities has motivated me to get my own, personal website
    now 😉

  11. WilliamSoorp表示:

    https://edwithoutdoctorprescription.pro/# meds online without doctor prescription

  12. Eugenehaupe表示:

    mexican mail order pharmacies mexican pharmaceuticals online mexico pharmacy

  13. Eugenehaupe表示:

    ed drugs natural remedies for ed drugs for ed

  14. Eugenehaupe表示:

    online pharmacy india online shopping pharmacy india indian pharmacy paypal

  15. Получи права управления автомобилем в лучшей автошколе!
    Стремись к профессиональной карьере вождения с нашей автошколой!
    Успей пройти обучение в лучшей автошколе города!
    Учись правильного вождения с нашей автошколой!
    Стремись к безупречным навыкам вождения с нашей автошколой!
    Научись уверенно водить автомобиль у нас в автошколе!
    Достигай независимости и свободы, получив права в автошколе!
    Прояви мастерство вождения в нашей автошколе!
    Обрети новые возможности, получив права в автошколе!
    Приведи друзей и они получат скидку на обучение в автошколе!
    Стань профессиональному будущему в автомобильном мире с нашей автошколой!
    Заводи и научись водить автомобиль вместе с нашей автошколой!
    Улучшай свои навыки вождения вместе с профессионалами нашей автошколы!
    Запиши обучение в автошколе и получи бесплатный консультационный урок от наших инструкторов!
    Стремись к надежности и безопасности на дороге вместе с нашей автошколой!
    Прокачай свои навыки вождения вместе с лучшими в нашей автошколе!
    Завоевывай дорожные правила и навыки вождения в нашей автошколе!
    Стань настоящим мастером вождения с нашей автошколой!
    Накопи опыт вождения и получи права в нашей автошколе!
    Пробей дорогу вместе с нами – закажи обучение в автошколе!
    автошкола васильківська http://www.avtoshkolaznit.kiev.ua .

  16. WilliamSoorp表示:

    http://medicinefromindia.store/# pharmacy website india

  17. WilliamSoorp表示:

    https://edpill.cheap/# ed pills cheap

  18. Undeniably believe that which you stated. Your favorite reason appeared to be on the web the easiest thing to be aware of.

    I say to you, I certainly get irked while people consider worries that they plainly don’t know about.
    You managed to hit the nail upon the top as well as defined out the whole thing without having side-effects , people could
    take a signal. Will probably be back to get more.
    Thanks

  19. WilliamSoorp表示:

    https://canadianinternationalpharmacy.pro/# maple leaf pharmacy in canada

  20. Eugenehaupe表示:

    top 10 online pharmacy in india buy prescription drugs from india mail order pharmacy india

  21. Eugenehaupe表示:

    best non prescription ed pills ed pills without doctor prescription prescription meds without the prescriptions

  22. WilliamSoorp表示:

    http://edwithoutdoctorprescription.pro/# legal to buy prescription drugs without prescription

  23. Eugenehaupe表示:

    buying prescription drugs in mexico mexican online pharmacies prescription drugs mexican mail order pharmacies

  24. Eugenehaupe表示:

    mexican border pharmacies shipping to usa mexican mail order pharmacies mexican mail order pharmacies

  25. WilliamSoorp表示:

    https://canadianinternationalpharmacy.pro/# canadadrugpharmacy com

  26. Eugenehaupe表示:

    drugs for ed buy ed pills ed medication online

  27. GeorgeLierm表示:

    Fences serve multiple purposes, commencement from providing safety and private to enhancing the aesthetics of a property. Yet, like any structure, fences instruct repair, occasional repairs, and now even supplanting to ensure they continue to fulfill their intended functions. In this article, we’ll delve into the diverse services offered close to professional impartial companies, including patch, institution, and replacement.

    Non-aligned Mend Services:
    Over conditions, fences can suffer check compensation due to out of sorts exposure, aging, or unpremeditated damage. Unrefined issues include perverse or rotted wood, tendency posts, disintegrated panels, loose hardware, and rusted metal components. Master hold at bay servicing services lecture these issues right away to resuscitate the fence’s structural unity and appearance. Skilled technicians assess the damage, recommend suitable repairs, and efficiently gain over the requisite duty, whether it involves replacing damaged sections, reinforcing untenable spots, or fixing hardware. Close addressing issues at the crack, uncommitted repair services alleviate prolong the lifespan of the fence and impede more national damage.
    fence replacement

    Separate Station Services:
    Whether you’re installing a new fence in place of keeping, monasticism, or aesthetic reasons, professional wall installation services insure a hassle-free convert from start to finish. These services typically on with a consultation to chat about the shopper’s needs, preferences, and property specifications. Based on this report, experts put forward satisfactory independent materials, styles, and designs that completion the resources’s architecture and meet the desired functionality. Able installers hold all aspects of the induction, from plot preparation and collection context to panel or picket disposition and absolute adjustments. During entrusting the burglary to wise professionals, property owners can wait for a long-wearing, fittingly installed railings that enhances contain pray and land value.

    Bound Replacement Services:
    When a unprejudiced reaches the end of its lifespan or sustains irreparable check compensation, replacement may be the most serviceable solution. Parry replacement services count in removing the existing fence and installing a untrodden ditty tailored to the shopper’s preferences and belongings requirements. Knowledgeable keep companies proffer a broad line of fencing materials, including wood, vinyl, aluminum, chain-link, and composite options, allowing estate owners to on the most opportune option based on durability, upkeep requirements, and budget. With meticulous prominence to detail and quality craftsmanship, ward replacement services make safe a seamless conversion to a recent, sound circumscribe that meets the property’s needs and enhances its appeal.

    Conclusion:
    From repairing minor damages to installing new fences and replacing worn-out structures, professional encircle services engage a crucial situation in maintaining the functionality, display, and value of residential and commercial properties. Away partnering with sagacious professionals, means owners can enjoy harmoniousness of positive crafty that their fencing needs are in capable hands, ensuring long-lasting, drawing fences that be in the service of their intended purposes effectively.

  28. WilliamSoorp表示:

    http://certifiedpharmacymexico.pro/# mexico drug stores pharmacies

  29. Eugenehaupe表示:

    new ed pills male ed drugs ed pills that really work

發佈留言

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