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,146,547 Responses

  1. Pretty! This has been an incredibly wonderful post.
    Thank you for providing this info.

  2. The 10 Most Scariest Things About Birth Injury Attorneys birth injury attorney

  3. Lisa表示:

    10 Quick Tips For Demo Slot pg slot demo (Lisa)

  4. 10 Best Mobile Apps For Cerebral Palsy Compensation Cerebral palsy lawsuits

  5. shaik表示:

    Your mode of describing everything in this piece of writing is actually fastidious, all can easily understand it,
    Thanks a lot https://shaik.ca/fr/qui-sommes-nous/

  6. https://pureganics.org, a popular skincare brand, has been gaining attention in the beauty industry for its natural and organic products.

  7. Drug information. Effects of Drug Abuse.
    cost cheap colchicine tablets
    All what you want to know about drugs. Read now.

  8. Kudos, An abundance of postings!

  9. You’ll Be Unable To Guess Personal Injury Case’s Secrets personal injury

  10. Leonie表示:

    10 Things You’ll Need To Learn About Online Sites For Shopping In Uk Contemporary Style Vanity Light – Leonie

  11. 9 Lessons Your Parents Taught You About Upvc Window Repair Near Me
    Window repair near me

  12. What’s The Job Market For Uk Online Phone Shopping Sites Professionals?
    uk online phone shopping Sites

  13. Just desire to say your article is as amazing. The clarity in your post is simply cool and i
    could assume you are an expert on this subject. Well with your permission let
    me to grab your RSS feed to keep updated with forthcoming post.
    Thanks a million and please keep up the gratifying work.

  14. Ingeborg表示:

    Where Can You Find The Most Effective Shopping Online
    Uk Information? Thick Bath Sheet Towel (Ingeborg)

  15. The 10 Scariest Things About Online Shopping Stores
    List online shopping stores list

  16. Vince表示:

    The Most Worst Nightmare About Upvc Front Doors Get
    Real upvc door fittings (Vince)

  17. Agueda表示:

    Guide To Double Glazing Near Me: The Intermediate Guide In Double Glazing Near Me double
    glazing near me – Agueda

  18. Hi! This is kind of off topic but I need some guidance from an established blog.
    Is it hard to set up your own blog? I’m not very techincal but I can figure things out pretty fast.
    I’m thinking about creating my own but I’m not sure where to start.

    Do you have any points or suggestions? Cheers

  19. eidoo-app.com表示:

    Just place an advance order for cards through your eidoo https://https://eidoo-app.com//, and it will to be automatically attached to any account.

  20. Double Glazing Near Me Tools To Streamline Your Daily Life Double Glazing Near Me Trick Every Individual
    Should Be Able To double Glazing near Me

  21. Wonderful beat ! I would like to apprentice while you amend your website, how can i subscribe for
    a blog site? The account helped me a acceptable deal.
    I had been tiny bit acquainted of this your broadcast offered bright clear idea

  22. Markcex表示:

    Пожалуйста, ближе к делу.
    Сняла койко – трудоустройство в квартире. Сняла помещение для отдыха в типовом договоре не прописано, https://crach.7bb.ru/ как я буду оплачивать аренду.

  23. bokep viral表示:

    Cool blog! Is your theme custom made or did you download it from somewhere?
    A theme like yours with a few simple adjustements would really
    make my blog shine. Please let me know where you got your theme.
    Appreciate it

  24. Chet表示:

    A Look At The Ugly Truth About Best Online Shopping Sites London 1X2 Hdmi Splitter (Chet)

  25. A Handbook For Replacement Upvc Window Handles From Start To Finish upvc window repair near me

  26. Wow that was strange. I just wrote an incredibly long comment but after I clicked submit my comment didn’t appear.
    Grrrr… well I’m not writing all that over again. Anyhow,
    just wanted to say great blog!

  27. Williambet表示:

    Скачать свежие новинки песен https://muzfo.net 2024 года ежедневно. Наслаждайтесь комфортным прослушиванием, скачивайте музыку за пару кликов на сайте.

  28. 10 Life Lessons We Can Take From Mobile Car Diagnostics diagnostic Tests (mylivingplan.com)

  29. 10 Misconceptions That Your Boss May Have About Railroad Injuries Attorneys Railroad injuries lawsuits

發佈留言

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