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,198,980 Responses

  1. 5 Killer Quora Answers On Window Replacement Near Me window replacement near me

  2. lawsuit表示:

    7 Tips About Federal Employers That No One Will Tell You lawsuit

  3. I’m gone to tell my little brother, that he should also go to see this website on regular basis to take updated from hottest news.

  4. arlennizo表示:

    12 Stats About Boot Scooter To Make You Think About The Other
    People arlennizo

  5. betflik 8k表示:

    My coder is trying to persuade me to move to .net from PHP.
    I have always disliked the idea because of the expenses.
    But he’s tryiong none the less. I’ve been using WordPress on several
    websites for about a year and am anxious about switching to
    another platform. I have heard great things about blogengine.net.

    Is there a way I can import all my wordpress posts
    into it? Any help would be really appreciated!

  6. Hi there friends, how is all, and what you want
    to say concerning this piece of writing, in my view its genuinely remarkable designed for me.

  7. The DeSantis campaign is keenly aware that the multiple criminal indictments against Mr. Trump have only intensified his support among many Republican 무료웹툰사이트

  8. Some Fast Ways To Choose A $5,000 Mortgage Loan 200만원 대출

  9. BomesJoype表示:

    Lorem Ipsum has been the industry’s standard dummy text https://joancanals.es/zboiqx of type and scrambled it to make a type specimen book.

  10. Drugs information sheet. Generic Name.
    buying cheap arimidex pills
    Actual information about pills. Read information here.

  11. The 10 Most Terrifying Things About Slot Demo Princess X1000 Demo Princess (https://Cs-Upgrade.Top/)

  12. 10 Methods To Build Your Affordable SEO Uk Empire affordable seo packages

  13. Drugs prescribing information. Effects of Drug Abuse.
    cost of cheap verapamil without insurance
    Some trends of medicine. Read here.

  14. The People Who Are Closest To Motorcycle Accident Settlement Share Some Big
    Secrets motorcycle accident attorney (lamerpension.co.kr)

  15. Medication information sheet. What side effects can this medication cause?
    order generic xenical prices
    All what you want to know about drug. Read now.

  16. Is Your Company Responsible For An Double Glazed Doors Near Me Budget?
    12 Best Ways To Spend Your Money Double Glazing Window Handles

  17. hb88boats表示:

    Very nice post. I just stumbled upon your blog and wanted to say that I’ve
    truly enjoyed surfing around your blog posts. After
    all I will be subscribing to your feed and I hope you write again soon!

  18. The Where And Abouts Of Bad Credit Home Equity Loan 농협 무직자 대출

  19. Hello, i read your blog from time to time and i own a similar one and
    i was just curious if you get a lot of spam responses?
    If so how do you reduce it, any plugin or anything you can recommend?
    I get so much lately it’s driving me insane so any support is very much appreciated.

    Also visit my blog post … Lottery Defeater Software

  20. The Biggest Problem With Glass Replacement Windows And How You Can Solve It Replacement window Locks

  21. Приветствую. Может кто знает, где почитать полезные статьи о недвижимости? Сейчас читаю https://vortex-los.ru

  22. Pills information leaflet. Cautions.
    where to get generic atomoxetine prices
    All news about meds. Get now.

  23. Why You Should Concentrate On Enhancing Medical Malpractice Compensation medical malpractice attorneys (http://www.datevinden.nl)

  24. rikvip表示:

    It’s in fact very complex in this busy life to listen news on Television, so I simply
    use web for that purpose, and get the newest news.

  25. 5 Clarifications On Railroad Injuries Settlement Railroad Injuries Law Firm

  26. 20 Inspiring Quotes About Peugeot 3008 Key Fob Peugeot Remote key replacement

  27. Всем привет! Подскажите, где почитать полезные блоги о недвижимости? Сейчас читаю https://vortex-los.ru

  28. Всем привет! Подскажите, где найти полезные блоги о недвижимости? Сейчас читаю https://vortex-los.ru

  29. dewagg表示:

    I don’t know whether it’s just me or if perhaps everyone else experiencing issues with your site.

    It looks like some of the written text within your posts are running off the screen. Can somebody else please provide feedback and
    let me know if this is happening to them as well?

    This might be a problem with my web browser because I’ve had this happen previously.
    Cheers

發佈留言

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