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,145,451 Responses

  1. wik.co.kr表示:

    What Is The Reason Adding A Key Word To Your Life Will Make All The Impact backlink builder
    software (wik.co.kr)

  2. A Brief History Of Upvc Windows Repair History Of
    Upvc Windows Repair upvc window repairs near me – wavedream.wiki

  3. The Most Significant Issue With CSGO Cases Highest Roi And
    How You Can Solve It operation phoenix weapon case

  4. clutch Case表示:

    How To Design And Create Successful CSGO Case New Instructions For Homeschoolers From Home clutch Case

  5. Daga表示:

    We’re a group of volunteers and opening a new scheme in our community.
    Your web site provided us with useful info to work on. You’ve performed a formidable process and
    our whole group will probably be grateful to you.

  6. Что такое Kraken!? Беспрепятственно развивающаяся торговая платформа даркнета. Те, кто хоть миг в своей жизни был по ту сторону интернета знают, насколько безграничен мир темной сети. По сути это тот же самый интернет к которому мы привыкли, только еще лучше — здесь не действуют запреты и ограничения. Здесь, http://en.sulseam.com/bbs/board.php?bo_table=free&wr_id=198678 в подпольном интеренте очень много разных ресурсов плохих и хороших, качественных и нет. Каждый выбирает себе то, что ему по душе. А ты переходи в мир безгроничного постоянного блаженства – переходи на Kraken!

  7. HenryEsoma表示:

    Found a captivating read that I’d like to recommend to you http://wmrp.listbb.ru/viewtopic.php?f=51&t=625

  8. Vimeo表示:

    Three Reasons Why Your Shopping Online Sites List Is Broken (And How To Fix It) Vimeo

  9. The 10 Scariest Things About Upvc Repairs Near Me upvc repairs Near me

  10. 20 Best Tweets Of All Time About SEO Tool Vps seo improvement Tools

  11. undress ai表示:

    I am really loving the theme/design of your web site.
    Do you ever run into any browser compatibility
    problems? A number of my blog visitors have complained about my site not operating correctly in Explorer
    but looks great in Chrome. Do you have any suggestions to help
    fix this problem?

  12. malpractice表示:

    Malpractice Settlement Tools To Make Your Daily Lifethe One Malpractice
    Settlement Technique Every Person Needs To Be Able
    To malpractice

  13. Hey! Someone in my Myspace group shared this website with us
    so I came to give it a look. I’m definitely loving the information. I’m book-marking and will be tweeting
    this to my followers! Exceptional blog and wonderful design and style.

  14. The 10 Scariest Things About Double Glazing Companies Near Me Double glazing companies near me

  15. 10 Meetups About New Upvc Door You Should Attend types Of upvc door hinges

  16. I am genuinely glad to read this weblog posts which consists of tons of valuable data,
    thanks for providing such data.

  17. Question: How Much Do You Know About Misted Double Glazing Repairs
    Near Me? Double glazed units

  18. bokep jepang表示:

    If some one needs expert view regarding blogging then i recommend him/her to pay a visit this weblog,
    Keep up the pleasant job.

  19. I like the helpful information you supply on your articles.
    I’ll bookmark your weblog and test once more right
    here regularly. I am moderately sure I’ll be told
    many new stuff right right here! Best of luck for the following!

  20. law表示:

    Veterans Disability Lawyers Tools To Ease Your Everyday Lifethe Only Veterans Disability Lawyers
    Trick Every Person Should Learn law

  21. Joshuafug表示:

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

  22. Katie表示:

    Hello, i think that i saw youu visited my wwblog sⲟ i came to “return the favor”.I’m attempting tօ find things to enhance my site!I suppose іtѕ ᧐k tο uѕе somme of yօur ideas!!

    My web-site shop Gravy & Stock (Katie)

  23. See What Pram Stroller 2 In 1 Tricks The Celebs Are Making
    Use Of pram stroller 2 in 1

  24. ThomasFlomi表示:

    ובעלות גוף חטוב, בחורות כמותן לא תמצא בשום מקום אחר. אתה יכול לבחור את הבחורה מתוך היצע גדול של בחורות סקסיות ממדינות שונות, יחסים רצינית עם הנשים הללו. עיסוי אירוטי בפתח תקווה ללא מחויבויות הוא ברכה בקרב גברים מודרניים! אחרי הכל, הנשים היפהפיות מוכנות Tel Aviv escorts services for men seeking love

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

  26. Hello just wanted to give you a quick heads up and let you know a few of the images aren’t loading properly.
    I’m not sure why but I think its a linking issue.
    I’ve tried it in two different browsers and both show the same outcome.

發佈留言

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