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,368,122 Responses

  1. Bookmarks表示:

    hello there and thank you for your info – I’ve definitely picked up something new from right here.
    I did however expertise a few technical points using this website, as
    I experienced to reload the site a lot of times previous to I could get it to load properly.
    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
    can damage your high-quality score if ads and marketing with
    Adwords. Well I’m adding this RSS to my e-mail and can look out for a lot more of your respective interesting content.
    Ensure that you update this again soon..

    Here is my web-site – Bookmarks

  2. Bookmarks表示:

    Thank you for helping out, superb information.

    Look at my blog post … Bookmarks

  3. Bookmarks表示:

    What is New U Life SOMADERM Transdermal Gel.

    Also visit my blog post – Bookmarks

  4. USP human growth hormonal agent (somatropin).

    Here is my homepage :: functional mushroom gummies

  5. Allow me reveal you in my testimonial of NewULife.

    my web page: euphoria mushroom gummies

  6. NewULife Ranks. Welcome to my NewUlife Review.

    Also visit my web blog :: cbd muscle balm pregnancy

  7. BarryDof表示:

    https://rybelsus.shop/# buy rybelsus online

  8. Hiya, I’m really glad I’ve found this information. Today bloggers publish just about gossips and net and this is really irritating.
    A good web site with interesting content, that’s what I
    need. Thank you for keeping this site, I will be visiting
    it. Do you do newsletters? Can’t find it.

    Take a look at my webpage – quality daycare services

  9. In this instance, the life insurance company’s money.

    Here is my web-site functional mushroom gummies

  10. Erica表示:

    solar energy advantages and disadvantages quizlet (Erica) plans explained,
    with Canna Campbell.

  11. Sometimes accidents leave you shocked, yet nothing else.

    Also visit my web site – how to choose The best personal injury lawyer

  12. Zoila Hincks表示:

    10 Simple Steps To Start Your Own Clitoris Vibrator Business best clitoral stimulator (Carri)

  13. 5 Killer Quora Answers To Private Psychiatrist Ipswich Private Psychiatrist

  14. Keep this going please, great job!

    my web-site … Choosing day care

  15. Bookmarks表示:

    NewULife Ranks. Invite to my NewUlife Evaluation.

    my web site … Bookmarks

  16. Keyword Research – 3 Keys To Locating A Successful Keyword 구글상위노출 업체

  17. This post offers clear idea in favor of the new visitors of blogging,
    that really how to do running a blog.

  18. Elizbeth Buie表示:

    5 Facts Wall Mounted Fireplace Is Actually A Good Thing electric wall mounted fireplace

  19. вывод из запоя на дому ростов недорого http://vyvod-iz-zapoya-rostov18.ru/ .

  20. вывод из запоя дешево ростов на дону вывод из запоя дешево ростов на дону .

  21. Gia表示:

    11 Ways To Completely Revamp Your Cheap Wood Burning Stoves garden shed with wood burner [Gia]

  22. I will right away grasp your rss as I can not to find your e-mail subscription hyperlink or newsletter service.
    Do you have any? Please let me recognise in order that I could
    subscribe. Thanks.

  23. LeroyAcuff表示:

    Профессиональный сервисный центр ближайший сервисный центр по ремонту телефонов где можно починить телефон

  24. This paragraph offers clear idea designed for the new people
    of blogging, that in fact how to do running a blog.

  25. 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 advise?
    I get so much lately it’s driving me insane so any help is very much appreciated.

    Check out my web-site – family child care

發佈留言

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