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,675,064 Responses

  1. Тут можно преобрести пожаростойкие сейфы сейф противопожарный

  2. Тут можно преобрести огнестойкие сейфы несгораемый сейф

  3. Тут можно преобрести несгораемые сейфы купить сейф огнестойкий

  4. промокод на подключение продамуса https://prodamus-promokod21.ru/ .

  5. Completed Reading a Blog Post: A Formal Reply to the Comment
    Section and an Invitation to Join “KING855”

    ‘After comprehensively studying the blog post, I would like to offer the
    following reply to the comment .

    Your opinions regarding the issue were quite intriguing .

    I found myself in concurrence with a number of the points
    you raised .

    It is encouraging to witness such an engaging exchange
    taking place .

    If you are keen in additional investigating this
    theme, I would warmly urge you to join the “KING855” network .
    There , you will have the chance to engage with kindred spirit individuals and delve deeper into these intriguing
    subjects.

    I am confident your participation would be a valuable
    addition to the discourse .

    Appreciate your contribution , and I look forward to the prospect of extending
    this enlightening dialogue .

    My blog post; online baccarat

  6. Тут можно преобрести сейф огнестойкий в москве сейф жаростойкий

  7. Тут можно преобрести сейфы от пожара огнестойкие сейфы

  8. Тут можно преобрести купить несгораемый сейф купить сейф огнестойкий

  9. Profix Bot表示:

    Oh my goodness! Awesome article dude! Thank you, However
    I am encountering problems with your RSS. I don’t know why I am
    unable to join it. Is there anyone else getting the
    same RSS problems? Anyone that knows the solution will you kindly respond?

    Thanks!!

  10. Fretonbit App表示:

    Amazing! Its really remarkable post, I have got much clear idea about from this paragraph.

  11. Shelly表示:

    I do not even know how I ended up here, but I thought this post was good.
    I do not know who you are but certainly you are going to a famous blogger if you aren’t already 😉 Cheers!

  12. You’ve made your stand pretty clearly.!

    Here is my website; スーパーコピー バッグ 激安 6畳 (http://www.cqcici.com/comment/html/?28171.html)

  13. Medication information sheet. What side effects can this medication cause?
    how to get generic cozaar pills
    All news about pills. Read now.

  14. cat888表示:

    I think the admin of this website is in fact working hard for his web
    site, since here every stuff is quality based data.

  15. Thank you for some other wonderful article. The place else could anyone get that kind of info in such a perfect approach
    of writing? I’ve a presentation subsequent week, and I’m at the search for such info.

  16. Syreeta表示:

    We stumbled over here different website and
    thought I might check things out. I like what I see so now i am
    following you. Look forward to looking over your web page repeatedly.

  17. I constantly emailed this webpage post page to all my
    friends, since if like to read it then my friends will too.

  18. Great work! This is the type of information that are supposed to be shared across the web.

    Disgrace on the search engines for now not positioning this post higher!
    Come on over and discuss with my web site . Thank you =)

  19. Really enjoyed this post about Lucky Jet. It’s one of
    those games that sounds easy but can be quite strategic when you
    try to figure out the best strategy. Thanks for putting this
    together!

  20. id=”firstHeading” class=”firstHeading mw-first-heading”>Search гesults

    Hеlp

    English

    Tools

    Tools
    movе to siebar hide

    Actions

    Generaⅼ

    Aⅼso visit mʏ web site รูปพวงหรีดแสดงความเสียใจ

  21. Dannyunoto表示:

    Сопровождение мужчин — это особая услуга, которая может включать в себя как деловые, так и личные аспекты.
    В современном мире многие мужчины ищут профессионалов, которые могут помочь им в различных сферах жизни:
    от бизнес-мероприятий до социальных встреч – девушка на час

  22. Excellent article! I truly enjoyed your insights on safe
    gambling habits. It’s vital to be informed before diving into the world of
    토토 용어 and non-regulated betting platforms.
    Your readers could also gain from to browse tootooasis.com for in-depth 토토사이트 검색 and betting playground information. The platform offers detailed
    articles that can benefit both newcomers and pro bettors more efficiently explore the betting
    environment. Visit https://totooasis.com for more details.

  23. toryvonstott表示:

    Как специалист, могу оказать помощь. Я специально зарегистрировался, чтобы поучаствовать в обсуждении.
    Нару?жная рекла?ма – графическая, текстовая, или иная информация продвигающего характера, она размещается на особых временных или стационарных конструкциях, размещенных на открытой местности, но это еще не все, на внешних поверхностях зданий, сооружений, на элементах уличного оборудования, над проезжей частью улиц и ценен или на них самих, https://rostov-gravity.mirtesen.ru/blog/43964770526/Neonovyie-vyiveski-v-naruzhnoy-reklame-stante-esche-yarche-?utm_referrer=mirtesen.ru а также на автозаправочных станциях (АЗС).

  24. hoho表示:

    You actually make it seem so easy with your presentation however I find this topic to be actually one thing that I feel I might never understand.
    It kind of feels too complex and extremely wide for me.
    I’m looking ahead to your subsequent publish, I’ll attempt
    to get the hold of it!

  25. Does your website have a contact page? I’m having problems locating it but, I’d like to send you an email.
    I’ve got some suggestions for your blog you might be interested in hearing.

    Either way, great site and I look forward to seeing it expand over time.

  26. you’re in point of fact a just right webmaster. The website loading
    velocity is incredible. It sort of feels that you’re doing any unique trick.

    Moreover, The contents are masterwork. you’ve done a fantastic activity in this
    topic!

發佈回覆給「Dannyunoto」的留言 取消回覆

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