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,117,008 Responses

  1. WilliamSoorp表示:

    https://medicinefromindia.store/# indian pharmacy online

  2. You can easily download the savefrom.net application.

  3. sigaribet表示:

    Amazing! Its actually amazing article, I have got much clear idea on the topic of from this article.

  4. WilliamSoorp表示:

    http://certifiedpharmacymexico.pro/# mexican rx online

  5. Hi there friends, good paragraph and fastidious urging commented here, I am in fact enjoying by these.

  6. WilliamSoorp表示:

    https://canadianinternationalpharmacy.pro/# safe canadian pharmacies

  7. WilliamSoorp表示:

    https://canadianinternationalpharmacy.pro/# ed drugs online from canada

  8. Заказать аттестат – прекрасная возможность получить важный бумагу. Это быстро и удобно.

  9. xxx porn free表示:

    Seo and bandmates’ outfits for the advertising cycle of “I Know” (Korean: 난 알아요 RR: Nan Arayo) involved vibrant streetwear
    these types of as outsized T-shirts and sweatshirts, windbreakers, overalls worn with
    a single strap, overalls worn with a single pant leg rolled up,
    and American athletics team jerseys. In an age of mass communication,
    gentle electric power (pursuing one’s aims by persuading stakeholders
    utilizing cultural and ideological energy) is regarded as a more powerful
    and pragmatic diplomatic tactic than the regular diplomatic technique tough electricity
    (obtaining what a person wishes from stakeholders by direct intimidation such as armed service menace and economic sanctions).

    Cultural diplomacy by means of K-pop is a kind of tender power.
    Xbox One arrives with the Kinect two. (the new version of
    the Kinect sensor), a single wireless controller, a mono headset, a Category 2 4K-rated HDMI cable,
    a electrical power brick and a energy cord. Two instance subgroups are Super Junior-K.R.Y.,
    which consists of Super Junior users Kyuhyun,
    Ryeowook, and Yesung, and Super Junior-M, which
    turned 1 of the very best-selling K-pop subgroups in China.
    Sometimes sub-models or sub-teams are formed among present users.

    Look into my web page: xxx porn free

  10. AndresBef表示:

    Fences look after the needs of a variety of purposes, from providing safety and privacy to enhancing the strength of a property. However, like any structure, fences require keep, additional repairs, and every now unvaried replacement to assure they carry on with to fulfill their intended functions. In this portion, we’ll delve into the diverse services offered about skilled restrict companies, including patch, coronation, and replacement.

    Divert Condition Services:
    All over outdated, fences can suffer abrasion and tear due to out of sorts unmasking, aging, or unpremeditated damage. Common issues encompass perverse or rotted wood, tendency posts, docile panels, lax tools, and rusted metal components. Master hold at bay mend services talk to these issues promptly to reconstruct the fence’s structural integrity and appearance. Skilled technicians assess the indemnity, persuade suitable repairs, and efficiently gain visible the of the essence work, whether it involves replacing damaged sections, reinforcing untenable spots, or fixing hardware. Past addressing issues at the crack, uncommitted put services help string out the lifespan of the independent and impede more extensive damage.
    enclose replacement

    Divert Station Services:
    Whether you’re installing a modish fence instead of asylum, retirement, or aesthetic reasons, official barrier installation services ensure a hassle-free convert from start to finish. These services typically on with a consultation to about the shopper’s needs, preferences, and mark specifications. Based on this report, experts recommend seemly fence materials, styles, and designs that crew the assets’s architecture and tourney the desired functionality. Experienced installers hold all aspects of the crowning, from site preparation and post setting to panel or vidette location and final adjustments. Not later than entrusting the area to experienced professionals, property owners can foresee a durable, suitably installed circumscribe that enhances curb pray and resources value.

    Bound Replacement Services:
    When a fence reaches the put to death of its lifespan or sustains irreparable damage, replacement may be the most efficient solution. Vacillating replacement services subsume removing the existing hedge and installing a revitalized inseparable tailored to the patient’s preferences and oddity requirements. Knowledgeable fence companies put forward a considerable range of fencing materials, including wood, vinyl, aluminum, chain-link, and composite options, allowing estate owners to elect the most applicable option based on durability, sustenance requirements, and budget. With punctilious prominence to detail and status craftsmanship, uncommitted replacement services make safe a seamless change to a recent, principled circumscribe that meets the idiosyncrasy’s needs and enhances its appeal.

    Conclusion:
    From repairing adolescent damages to installing virgin fences and replacing worn-out structures, licensed vacillating services stake a decisive r“le in maintaining the functionality, suggestion, and value of residential and commercial properties. Away partnering with experienced professionals, estate owners can take advantage of peace of mind knowing that their fencing needs are in capable hands, ensuring long-lasting, good-looking fences that act as their intended purposes effectively.

  11. Eugenehaupe表示:

    online shopping pharmacy india cheapest online pharmacy india п»їlegitimate online pharmacies india

  12. Your means of explaining everything in this paragraph is truly nice, every one be able to easily be aware of it, Thanks a lot.

  13. BennyNib表示:

    mexican rx online: mexican drugstore online – medication from mexico pharmacy

  14. Gaya district表示:

    threesome shirt

  15. Eugenehaupe表示:

    pharmacy website india buy prescription drugs from india india online pharmacy

  16. BennyNib表示:

    prescription drugs: cialis without a doctor prescription canada – prescription drugs online

  17. WilliamSoorp表示:

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

  18. Mldfut表示:

    doxycycline pills where to buy doxycycline without a prescription vibra-tabs without prescription

  19. WilliamSoorp表示:

    http://edpill.cheap/# erectile dysfunction pills

  20. WilliamSoorp表示:

    http://edpill.cheap/# cheap ed drugs

  21. investment表示:

    Whoa! This blog looks exactly like my old one! It’s on a totally different topic but it has pretty much the same page layout and design. Wonderful choice of
    colors!

  22. WilliamSoorp表示:

    https://canadianinternationalpharmacy.pro/# canada drugs online reviews

  23. AndresBef表示:

    Fences serve several purposes, commencement from providing refuge and privacy to enhancing the attraction of a property. Be that as it may, like any structure, fences be lacking conservation, occasional repairs, and every now even swapping to make sure they persist to fulfill their intended functions. In this article, we’ll delve into the several services offered not later than seasoned encircle companies, including adjust, solemnization, and replacement.

    Divert Repair Services:
    All over time, fences can suffer don and fly appropriate to unwell unmasking, aging, or unpremeditated damage. Unrefined issues encompass warped or rotted wood, leaning posts, disintegrated panels, lax hardware, and rusted metal components. Maven bound servicing services lecture these issues instantaneously to reimburse the rampart’s structural integrity and appearance. Skilled technicians assess the indemnity, propose satisfactory repairs, and efficiently gain out the of the utmost importance duty, whether it involves replacing damaged sections, reinforcing rickety spots, or fixing hardware. Close addressing issues at the crack, sidestep put services alleviate string out the lifespan of the uncertain and intercept more extensive damage.
    sidestep shape

    Fence Introduction Services:
    Whether you’re installing a fresh neutral instead of insurance, privacy, or aesthetic reasons, wizard wall fitting services safeguard a hassle-free procedure from start to finish. These services typically start off with a consultation to chat about the customer’s needs, preferences, and paraphernalia specifications. Based on this information, experts put forward fitting enclosure materials, styles, and designs that completion the resources’s architecture and tourney the desired functionality. Experienced installers handle all aspects of the crowning, from milieu preparation and dispatch milieu to panel or vidette disposition and closing adjustments. At hand entrusting the province to master professionals, property owners can wait for a firm, suitably installed fence that enhances restraint lure and land value.

    Stonewall Replacement Services:
    When a unprejudiced reaches the end of its lifespan or sustains irreparable check compensation, replacement may be the most efficient solution. Confine replacement services involve removing the existing unaligned and installing a untrodden ditty tailored to the customer’s preferences and oddity requirements. Professional keep companies offer a considerable line of fencing materials, including wood, vinyl, aluminum, chain-link, and composite options, allowing feature owners to elect the most opportune choice based on durability, maintenance requirements, and budget. With scrupulous regard to fact and importance craftsmanship, ward replacement services ensure a seamless transformation to a recent, reliable keep that meets the worth’s needs and enhances its appeal.

    Conclusion:
    From repairing adolescent damages to installing brand-new fences and replacing worn-out structures, licensed fence services engage a vital role in maintaining the functionality, suggestion, and value of residential and commercial properties. By partnering with experienced professionals, estate owners can take advantage of peace of intellectual crafty that their fencing needs are in competent hands, ensuring long-lasting, attractive fences that act as their intended purposes effectively.

  24. brazzers表示:

    Hi there friends, how is everything, and what you wish for to
    say on the topic of this article, in my view its really
    awesome for me.

  25. Tutors online表示:

    Every weekend i used to pay a quick visit this web site, because i wish for enjoyment, as
    this this web page conations actually pleasant funny data too.

  26. I have read so many articles or reviews concerning the blogger lovers however this piece of writing is really a fastidious paragraph, keep it up.

  27. WilliamSoorp表示:

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

  28. Edwardcloth表示:

    сантехник в краснодаре недорого https://keramogranit-krasnodar.ru/

  29. WilliamSoorp表示:

    http://medicinefromindia.store/# buy medicines online in india

發佈留言

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