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,156,345 Responses

  1. kontol表示:

    My spouse and I absolutely love your blog and find many of your post’s to be exactly what I’m looking for.
    Do you offer guest writers to write content to suit your needs?
    I wouldn’t mind publishing a post or elaborating on a
    few of the subjects you write concerning here.
    Again, awesome web site!

  2. repairer表示:

    What’s The Ugly Facts About Window Fixer London repairer

  3. 14 Questions You’re Afraid To Ask About Mesothelioma Compensation Mesothelioma Attorneys

  4. An asbestos Litigation lawyer
    can assist victims in filing a lawsuit against the company that exposed them.
    A lawsuit can assist victims in recovering compensation for medical expenses, lost wages and other damages.

  5. See What Uk Online Shopping Sites For Mobile Tricks The Celebs Are
    Utilizing uk online shopping sites for mobile

  6. Are You Responsible For An Small Sofa L Shape Budget? 10 Very Bad Ways To
    Invest Your Money gray l shape sofa (ww.invitel.co.kr)

  7. Five Killer Quora Answers To Online Home Shop Uk Discount Code Online Home Shop Uk Discount Code (Trademarketclassifieds.Com)

  8. The Best Motor Vehicle Lawsuit Gurus Are Doing Three Things motor vehicle accident lawsuits (https://images.google.ms/url?sa=t&url=https://vimeo.com/706763856)

  9. Danieldob表示:

    Приветствую. Подскажите, где найтиразные блоги о недвижимости? Сейчас читаю https://tent44.ru

  10. Medicament information. What side effects?
    cost cheap benicar for sale
    Everything what you want to know about medication. Get information here.

  11. Komentari su kao uputstvo za upotrebu – nekad pomazu, nekad zbunjuju.
    Chevrolet Blazer kombinuje eleganciju i performanse.
    U auto mi se vise stavljaju delovi nego gorivo.

  12. Hello! Do you know if they make any plugins
    to safeguard against hackers? I’m kinda paranoid about losing everything I’ve worked hard on. Any recommendations?

  13. The 10 Scariest Things About List Of Online Shopping
    Sites Uk list of online shopping sites uk

  14. How To Choose The Right Interactive Slots On The Internet evoplay slots Features

  15. The Top Workers Compensation Lawsuit That Gurus Use Three Things
    Workers’ Compensation (http://Www.Nobelpat.Com)

  16. baskili poset表示:

    Hello there, I found your website by means of Google whilst looking for a comparable subject,
    your website got here up, it seems good. I have bookmarked it in my google bookmarks.

    Hi there, simply become alert to your weblog through Google,
    and found that it’s truly informative. I am going to be careful for brussels.

    I’ll appreciate in the event you proceed this in future.
    Numerous people might be benefited out of your writing.
    Cheers!

  17. Please let me know if you’re looking for a article author for your blog.
    You have some really good articles and I think I would
    be a good asset. If you ever want to take some of the load off, I’d really like to write some material for your blog in exchange for a link back to mine.
    Please send me an e-mail if interested. Thanks!

  18. hey there and thank you for your info – I have certainly
    picked up anything new from right here. I did however expertise several technical points using this website, since I
    experienced to reload the site lots of times previous to I could get it to load correctly.
    I had been wondering if your web host is OK? Not that I’m
    complaining, but sluggish loading instances times will sometimes affect your placement in google and could
    damage your high quality score if advertising and marketing with Adwords.
    Anyway I am adding this RSS to my email and could look
    out for a lot more of your respective interesting content.
    Ensure that you update this again very soon.

  19. pepek becek表示:

    Hmm is anyone else having problems with the pictures on this
    blog loading? I’m trying to figure out if
    its a problem on my end or if it’s the blog. Any suggestions would
    be greatly appreciated.

  20. ai image表示:

    Nice blog here! Also your site loads up very fast!
    What host are you using? Can I get your affiliate link to your host?

    I wish my website loaded up as fast as yours lol

  21. A. The Most Common Bedford Door And Window Debate Isn’t As Black Or White As You Might Think Window Cleaning Service

  22. Five Car Accident Claim Projects To Use For Any Budget Car Accident Attorney

  23. The Lesser-Known Benefits Of Online Clothing Sites Uk cheapest Online shopping
    uk (maps.google.no)

  24. 15 Things You Don’t Know About Semi Truck Litigation semi truck accident law firm

  25. TAMPUNG99表示:

    Good way of explaining, and good piece of writing to get data about my presentation subject, which i am going to
    deliver in institution of higher education.

  26. Hey there! Quick question that’s entirely off topic. Do you know how to make your site mobile friendly? My site looks weird when viewing from my iphone4. I’m trying to find a theme or plugin that might be able to fix this problem. If you have any recommendations, please share. Many thanks!

  27. From Around The Web Here Are 20 Amazing Infographics About How To
    Get Diagnosis For ADHD how to get diagnosed with adhd In adulthood

發佈留言

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