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,142,577 Responses

  1. 10 Sites To Help You To Become An Expert In Outdoor Mobility Scooters Indoor Mobility Scooters

  2. Wonderful post! We will be linking to this great post
    on our site. Keep up the great writing.

  3. One of the best ways to do this iis by using a Checkatrade-approved
    plumer in Uk.

  4. 5 Killer Quora Answers To Slot Sound Effects
    slot Sound Effects

  5. Drug information leaflet. Generic Name.
    can i order generic pioglitazone pills
    All trends of medicine. Get here.

  6. 9 Lessons Your Parents Taught You About Slot Sites Slot sites (https://acharyacenter.com)

  7. Really want to say Now i am delighted that i happened in your page!

    https://www.telewizjazary.pl

  8. Click here表示:

    Hi there, all the time i used to check webpage posts here in the early hours
    in the break of day, because i love to find out more and more.

  9. Hi my loved one! I want to say that this article is amazing, nice written and come with almost all significant infos.
    I would like to look more posts like this .

    my blog post; java burn review

  10. 14 Smart Ways To Spend Leftover Window.Replacement Near Me Budget Replacement Window Locks

  11. lộ clip sex表示:

    This is really interesting, You’re a very skilled blogger.
    I’ve joined your rss feed and look forward to seeking more of
    your excellent post. Also, I’ve shared your web site in my social networks!

  12. What’s The Job Market For Slots For Fun Professionals?
    Slots for fun [https://Www.longisland.Com/profile/mittenfowl15]

  13. You could certainly see your skills within the article you write.
    The arena hopes for more passionate writers such as you who are not afraid to say how
    they believe. Always follow your heart.

  14. I love the info on your site. Thanks a bunch.

    https://www.polskibiznes.info

  15. 10 Best Facebook Pages Of All Time Slot Animations
    fair slots (images.google.co.il)

  16. Pretty nice post. I simply stumbled upon your blog and wished to mention that I have
    really enjoyed browsing your blog posts.
    In any case I’ll be subscribing on your feed and I am hoping you write once more soon!

  17. Wow that was unusual. I just wrote an extremely long comment but after
    I clicked submit my comment didn’t show up. Grrrr…
    well I’m not writing all that over again. Regardless, just wanted to say wonderful blog!

    Here is my web blog – مبل راحتی شیک

  18. From All Over The Web The 20 Most Amazing Infographics About Repairs To Double
    Glazed Windows window repairs

  19. 11 Ways To Totally Block Your Free Slots Mobile-Friendly Slots

  20. The 9 Things Your Parents Teach You About Online Shopping Sites Clothes Cheap online shopping sites
    (http://opp-hr.com/Bbs/board.php?bo_table=free&wr_id=1186)

  21. Vimeo表示:

    5 Laws That’ll Help The Online Shopping Industry
    Vimeo

  22. 15 Great Documentaries About Upvc Door Panels Replace Lock In Upvc Door

  23. GroverCon表示:

    Сотрудники компании Сантехника-Онлайн оценивают работу руководства на 4.1 из 5, на основании 165 оценок. Как сотрудники Сантехника-Онлайн оценивают возможности карьерного роста компании Отзывы от партнеров Сантехника Онлайн

  24. 5 Laws To Help The Slot Demo Zeus Gratis Industry Zeus 3 Free Slots

  25. Don’t Stop! 15 Things About Best Online Clothing Sites Uk We’re Sick Of
    Hearing Skar audio bass speaker

  26. Это обусловлено гораздо более сильной конкуренцией за попадание сайта в ТОП, ведь SEO на Западе существует дольше, и новых игроков становится все больше.

    My web page; продвижение сайта google

  27. bokep indo表示:

    If you desire to get much from this piece of writing then you have to apply these
    strategies to your won webpage.

  28. 네이버 아이디 구매 비실명 ID 계정 판매
    네이버 아이디 구매

發佈留言

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