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

  1. Eugenehaupe表示:

    india online pharmacy online pharmacy india indianpharmacy com

  2. zalayeta02表示:

    Hi to all, how is all, I think every one is getting more from
    this web page, and your views are pleasant in favor of new viewers.

    Here is my web page; zalayeta02

  3. I like it whenever people get together and share views. Great blog, continue the good work!

  4. BennyNib表示:

    pharmacies in mexico that ship to usa: buying prescription drugs in mexico online – medication from mexico pharmacy

  5. BennyNib表示:

    purple pharmacy mexico price list: best online pharmacies in mexico – buying prescription drugs in mexico

  6. WilliamSoorp表示:

    http://canadianinternationalpharmacy.pro/# buying drugs from canada

  7. Eugenehaupe表示:

    indianpharmacy com indian pharmacy online reputable indian pharmacies

  8. Eugenehaupe表示:

    buy prescription drugs without doctor ed pills without doctor prescription prescription drugs without doctor approval

  9. With thanks! Useful stuff.

    Feel free to surf to my website – Demo Slot Gacor Parah (https://demo-slot-gacor-parah.blogspot.com/)

  10. BennyNib表示:

    top 10 pharmacies in india: top 10 pharmacies in india – mail order pharmacy india

  11. WilliamSoorp表示:

    http://edwithoutdoctorprescription.pro/# prescription drugs without doctor approval

  12. Thank you for sharing your thoughts. I truly appreciate your efforts and I will
    be waiting for your further post thank you once again.

  13. BennyNib表示:

    reputable indian online pharmacy: best india pharmacy – best online pharmacy india

  14. Thanks very nice blog!

  15. WilliamSoorp表示:

    https://medicinefromindia.store/# top 10 online pharmacy in india

  16. WilliamSoorp表示:

    http://medicinefromindia.store/# reputable indian online pharmacy

  17. I think this is among the most vital info for me. And i’m glad reading your article.

    But wanna remark on some general things, The web site style is
    great, the articles is really excellent : D. Good job, cheers

  18. GeorgeLierm表示:

    Fences of use multiple purposes, starting from providing refuge and privacy to enhancing the strength of a property. However, like any make-up, fences press for maintenance, regular repairs, and now unvaried exchange to ensure they persist to fulfill their intended functions. In this write-up, we’ll delve into the divergent services offered by seasoned impartial companies, including adjust, solemnization, and replacement.

    Fence Repair Services:
    Once again time, fences can suffer damage satisfactory to weather risk, aging, or chance damage. Unrefined issues include warped or rotted wood, leaning posts, crushed panels, let go tools, and rusted metal components. Professional bound repair services lecture these issues instantaneously to restore the rampart’s structural integrity and appearance. Skilled technicians assess the expense, recommend proper repairs, and efficiently carry out the necessary duty, whether it involves replacing damaged sections, reinforcing untenable spots, or fixing hardware. Close to addressing issues at, sidestep repair services improve prolong the lifespan of the irresolute and ban more extensive damage.
    fence ordination

    Divert Station Services:
    Whether you’re installing a fresh stonewall for barrier, sequestration, or aesthetic reasons, official barrier placement 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 worth specifications. Based on this information, experts counsel satisfactory fence materials, styles, and designs that quorum the assets’s architecture and meet the desired functionality. Experienced installers handle all aspects of the ordination, from plot preparation and delivery setting to panel or observer disposition and unchangeable adjustments. Not later than entrusting the province to experienced professionals, estate owners can foresee a durable, properly installed circumscribe that enhances contain request and fortune value.

    Stonewall Replacement Services:
    When a fence reaches the put to death of its lifespan or sustains irreparable check compensation, replacement may be the most applied solution. Confine replacement services involve removing the existing fence and installing a revitalized in unison tailored to the shopper’s preferences and gear requirements. Expert cavil companies put forward a deviating range of fencing materials, including wood, vinyl, aluminum, chain-link, and composite options, allowing property owners to on the most opportune choice based on durability, sustenance requirements, and budget. With meticulous attention to list and importance craftsmanship, ward replacement services make safe a seamless change to a different, responsible fence that meets the worth’s needs and enhances its appeal.

    Conclusion:
    From repairing negligible damages to installing virgin fences and replacing worn-out structures, whiz vacillating services play a vital role in maintaining the functionality, display, and value of residential and commercial properties. By partnering with sagacious professionals, means owners can make use of peacefulness of intellectual knowing that their fencing needs are in talented hands, ensuring long-lasting, good-looking fences that act as their intended purposes effectively.

  19. Do you have a spam problem on this website; I also am a blogger,
    and I was wanting to know your situation; many of us have created some
    nice methods and we are looking to swap techniques with others, please shoot me an email if
    interested.

  20. BennyNib表示:

    buying prescription drugs in mexico: pharmacies in mexico that ship to usa – buying prescription drugs in mexico online

  21. WilliamSoorp表示:

    https://edpill.cheap/# drugs for ed

  22. check this表示:

    Thanks for any other great article. The place else may anyone get that type of information in such an ideal method of
    writing? I’ve a presentation subsequent week, and I’m at the search for such info.

  23. Eugenehaupe表示:

    over the counter erectile dysfunction pills medicine for erectile ed drug prices

  24. Eugenehaupe表示:

    canadian pharmacy 24 canadapharmacyonline canadian pharmacy world

  25. Howdy would you mind letting me know which web host you’re utilizing?
    I’ve loaded your blog in 3 different internet browsers and I must say
    this blog loads a lot faster then most. Can you recommend a good
    web hosting provider at a reasonable price? Kudos, I
    appreciate it!

  26. Jeffery表示:

    When someone writes an post he/she retains the plan of a user in his/her
    mind that how a user can know it. Therefore that’s why this article is great.
    Thanks!

  27. WOW just what I was looking for. Came here by searching
    for Ritalin kopen

  28. pionbet表示:

    Hello it’s me, I am also visiting this web page regularly, this site is really nice and the visitors are in fact sharing nice thoughts.

  29. Eugenehaupe表示:

    medications for ed cheap erectile dysfunction pills cures for ed

  30. argie表示:

    I don’t even know the way I ended up here, bᥙt I assumed tis ppost was once great.
    I do not rehognize who үou’re but definitely you arе going to а famous blogger shoild you are not already.
    Cheers!

發佈留言

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