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,433,693 Responses

  1. Elena Maynard表示:

    Amazing content, Kudos.

  2. warnetplay表示:

    Just want to say your article is as astounding.

    The clarity to your publish is just cool and that i could assume you are a professional
    in this subject. Well with your permission allow me to take hold
    of your RSS feed to stay updated with imminent post. Thank you one million and please keep up the enjoyable work.

  3. I read this post fully regarding the comparison of
    latest and preceding technologies, it’s remarkable article.

  4. lotto表示:

    Howdy, i read your blog fгom time to time and i оwn a similar one ɑnd i ԝаs ϳust curious if үou get a lot of spam
    feedback? Ӏf so how do yoս prevent it, any
    plugin оr anything you can recommend? I gеt ѕo mᥙch latеly
    it’ѕ driving me insane so any һelp іѕ very much appreciated.

    Here is my web blog :: lotto

  5. near by表示:

    %%

    Here is my homepage :: near by

  6. wordpress表示:

    hey there and thank you for your information –
    I have certainly picked up something new from right here.

    I did however expertise some technical points using this web site, since I experienced to
    reload the web site many 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 slow loading instances times will
    very frequently affect your placement in google and could damage your quality
    score if ads and marketing with Adwords. Anyway I am adding
    this RSS to my email and can look out for a lot more of your respective fascinating content.
    Make sure you update this again soon.

  7. Carlathund表示:

    gama casino онлайн
    https://oldforum.citysakh.ru/?talkid=18816
    Мы понимаем, что в мире азарта важна не только выигрышная стратегия, но и атмосфера игры. Поэтому Gama Casino создает вокруг вас атмосферу непередаваемого азарта и волнения. Это как таинственная маскарадная вечеринка, на которой каждый вращающийся барабан — это шаг к открытию новых миров. И Гама Казино — ваш проводник на этой захватывающей вечеринке!Gama Casino — не просто интернет-казино на русском языке, это эпицентр страсти и риска, где каждый Гама Казино игрок становится настоящим героем своей судьбы. Здесь, на нашем виртуальном азартном корабле, ваши желания и мечты воплощаются в жизнь с каждым вращением барабанов игровых автоматов.

  8. bokep memek表示:

    I was suggested this web site by my cousin. I’m not sure whether
    this post is written by him as no one else know such detailed about my
    difficulty. You’re amazing! Thanks!

  9. lotto表示:

    Hi! I қnow this is kinda оff topic but I wɑѕ wondering if
    you knew where I coᥙld locate ɑ captcha plugin foг my comment form?
    Ι’m uѕing tһe ѕame blog platform ɑs yours ɑnd I’m having trouble finding one?
    Thanks ɑ ⅼot!

    my site: lotto

  10. sitemap表示:

    Awesome! Itts truly aazing paragraph, I have got much clear
    idewa onn thee tpic of froim this article.

  11. Josephisofs表示:

    sildenafil oral jelly 100mg kamagra: buy Kamagra – Kamagra 100mg price

  12. Hello, after reading this remarkable paragraph i am
    also happy to share my know-how here with friends.

  13. sitemap表示:

    Apprecisting thhe time andd energy yyou puut int our
    website and inn deepth information you provide. It’s nice too clme across a blog every once iin a while that
    isn’t the same old reuashed information. Excellent read! I’ve saved you sitye and
    I’m adcing your RSS feeds to myy Gogle account.

  14. At this time it appears like Expression Engine is the top blogging platform available right now.
    (from what I’ve read) Is that what you are using on your blog?

  15. sitemap.xml表示:

    Thanks for thhe good writeup. It inn facht was a
    amusemebt acccount it. Glaance complexx tto faar added agreeble from you!
    However, howw could wwe be iin contact?

  16. Eric Primrose表示:

    Incredible a good deal of awesome material.

  17. %%

    Look into my web-site – Seat Key Replacement, Vn.Easypanme.Com,

  18. Charmain表示:

    %%

    my web site :: volvo v50 key (Charmain)

  19. Norefs.Com表示:

    %%

    Here is my web-site; Saab Key (Norefs.Com)

  20. Arturo表示:

    %%

    Also visit my website … saab 93 key programming (Arturo)

  21. %%

    Visit my blog post; become avon rep (dmskj.ff114.cn)

  22. Ingrid表示:

    %%

    Feel free to visit my website: electricians in ampthill (Ingrid)

  23. Jerri表示:

    10 Quick Tips About coffee bean coffee maker, Jerri, Machines Beans

  24. It’s remarkable to pay a visit this web site and reading
    the views of all friends about this piece of writing, while I am
    also zealous of getting experience.

發佈留言

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