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,412,471 Responses

  1. Peculiar article, totally what I wanted to find.

  2. That is very fascinating, You’re an excessively skilled blogger.
    I’ve joined your feed and stay up for in the
    hunt for more of your great post. Also, I have shared your
    site in my social networks

    my website: online poker ranking

  3. I like this site because so much utile stuff on here :D.

    Feel free to surf to my webpage … safest poker sites

  4. Mayra表示:

    window glass replacement corby (Mayra)

  5. This design is incredible! You obviously know how to keep a reader entertained.
    Between your wit and your videos, I was almost moved to start my own blog (well, almost…HaHa!) Wonderful job.

    I really enjoyed what you had to say, and more than that, how you presented
    it. Too cool!

  6. Hello, just wanted to tell you, I enjoyed this blog post.
    It was helpful. Keep on posting!

  7. Beatriz表示:

    %%

    Here is my blog – saab key programming (Beatriz)

  8. What’s up friends, nice paragraph and fastidious urging commented here, I am genuinely enjoying by these.

  9. Bill表示:

    Thank you so much for giving everyone an extraordinarily
    remarkable chance to read from this web site. It’s always
    so great plus stuffed with a good time for me and my office
    peers to visit the blog not less than 3 times in one week to read through the fresh
    items you will have. And indeed, I am also certainly
    fulfilled concerning the magnificent things served by you.

    Certain 4 areas on this page are basically the finest we’ve
    had.

    Feel free to visit my blog post: top poker sites (Bill)

  10. Josephisofs表示:

    sildenafil 100 mg prescription: ildenafil citrate – sildenafil citrate 50 mg

  11. Hmm is anyone else having problems with the pictures on this blog
    loading? I’m trying to find out if its a problem on my
    end or if it’s the blog. Any feed-back would be greatly appreciated.

  12. Are you looking to buy a verified Cash App account?
    Look no further! A verified Cash App account offers added security and peace of mind while
    conducting transactions. With a verified account,
    you can enjoy faster withdrawals and higher transaction limits.

    Don’t wait, get your verified Cash App account today!

  13. Kaylene表示:

    %%

    Also visit my page … replacement key volkswagen – Kaylene,

  14. I know this if off topic but I’m looking into starting my own blog
    and was curious what all is required to get set up? I’m assuming
    having a blog like yours would cost a pretty penny?

    I’m not very web smart so I’m not 100% certain. Any suggestions or advice
    would be greatly appreciated. Thank you

  15. syair sdy表示:

    It’s going to be end of mine day, however before end I am reading this enormous
    article to improve my experience.

  16. Why users still make use of to read news papers when in this technological world the whole thing is presented on net?

  17. It’s appropriate time to make some plans for
    the future and it is time to be happy. I’ve read this post and if I could I desire to suggest
    you few interesting things or tips. Perhaps you could write
    next articles referring to this article. I desire to read even more things about it!

  18. online slots表示:

    I’m really enjoying the design and layout of your website.

    It’s a very easy on the eyes which makes it much more
    pleasant for me to come here and visit more often. Did you hire out a designer
    to create your theme? Great work!

    my web site … online slots

  19. With havin so much content do you ever run into any problems of plagorism or copyright violation? My site has a lot of completely unique content
    I’ve either created myself or outsourced but it looks like a lot of it is popping it up all over the web without my agreement.
    Do you know any methods to help stop content
    from being ripped off? I’d certainly appreciate it.

    My page :: top poker sites

  20. gginjikwt表示:

    Приучайте себя мыслить конкретно.

    «Работа над собой», «Улучшение себя», «Искоренение своих недостатков» — слова красивые, но обычно за ними ничего не стоит. И тот, кто такими словами пользуется, чаще всего топчется на одном месте.

    «Вставайте, граф! Вас ждут великие дела!», «Утро начинается с зарядки», «Встал — убрал постель», «Вышел из дома — расправил плечи» — вещи простые и конкретные. И польза от таких мыслей, дельных распоряжений самому себе, — большая.

    https://batmanapollo.ru

  21. Harriet表示:

    asbestos cancer lawsuit lawyer mesothelioma (Harriet)

  22. Brigette表示:

    %%

    My homepage :: premium full spectrum (Brigette)

  23. شوخی表示:

    Hello I am so grateful I found your weblog, I really found you
    by mistake, while I was searching on Aol for something else, Regardless I am here now and would just like to say many thanks for
    a incredible post and a all round interesting blog
    (I also love the theme/design), I don’t have time to look over it all at the moment but I have book-marked it and also added in your RSS feeds, so
    when I have time I will be back to read a great deal more, Please do keep up
    the superb jo.

  24. Large表示:

    %%

    Here is my web blog – Large

  25. I’d like to find out more? I’d care to find out some additional information.

發佈留言

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