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,227,907 Responses

  1. Hi there! Do you know if they make any plugins to safeguard against hackers?
    I’m kinda paranoid about losing everything I’ve
    worked hard on. Any recommendations?

  2. Hi, i think that i saw you visited my site thus i came to “return the favor”.I am trying
    to find things to enhance my website!I suppose its
    ok to use a few of your ideas!!

  3. satta king表示:

    What’s up, after reading this amazing article i am as well delighted to share my experience here with colleagues.

  4. My relatives all the time say that I am wasting my time
    here at net, except I know I am getting familiarity
    every day by reading such nice articles.

  5. Sherryl表示:

    Right here is the perfect site for everyone who wants to find out about this topic.
    You understand a whole lot its almost tough to argue with you (not that I actually would want to…HaHa).
    You certainly put a brand new spin on a topic which has been discussed
    for many years. Great stuff, just excellent!

  6. If some one needs to be updated with latest technologies afterward he must be pay a visit this site and be up to date all the time.

  7. It is not my first time to visit this site, i am browsing this
    site dailly and get nice facts from here daily.

  8. I’ve been browsing online more than 3 hours today, yet I
    never found any interesting article like yours. It’s pretty worth enough
    for me. Personally, if all webmasters and bloggers
    made good content as you did, the net will be a lot more useful than ever before.

  9. This post will help the internet visitors for building up new blog or
    even a weblog from start to end.

  10. Thanks for the auspicious writeup. It actually used to
    be a leisure account it. Look complex to far added agreeable from you!
    However, how could we be in contact?

  11. Pretty section of content. I just stumbled upon your weblog and in accession capital
    to assert that I acquire actually enjoyed account your blog posts.
    Anyway I’ll be subscribing to your feeds and even I achievement you access consistently quickly.

  12. notes.io表示:

    I am in fact pleased to glance at this weblog posts which carries tons of helpful information, thanks for providing these kinds of information.

  13. I’m no longer sure where you are getting your information, but great topic.

    I needs to spend some time finding out more or understanding more.
    Thank you for great info I was in search of this info for my mission.

  14. cults3d.com表示:

    Hello i am kavin, its my first occasion to commenting anywhere, when i read this piece of writing i thought i could also create comment due to this brilliant piece of writing.

  15. Wow, incredible blog layout! How lengthy have you ever been running a blog for?
    you made running a blog look easy. The full glance of your
    site is excellent, let alone the content!

  16. I got this web site from my friend who informed me concerning
    this web site and now this time I am visiting this web site and reading very informative posts at this time.

  17. An outstanding share! I have just forwarded this onto a friend who was conducting a little homework on this.
    And he in fact bought me lunch simply because I found it
    for him… lol. So allow me to reword this…. Thanks for the meal!!
    But yeah, thanks for spending some time to discuss
    this issue here on your web site.

  18. It’s very straightforward to find out any matter on web as compared to books,
    as I found this paragraph at this site.

  19. If you desire to take a good deal from this paragraph then you
    have to apply these strategies to your won website.

  20. ski fahren表示:

    Nur aus dringenden betrieblichen oder in der Person des Arbeitnehmers liegenden Gründen ist
    eine Übertragung des Urlaubs aufs nächste Kalenderjahr statthaft; dieserfalls muss
    der Urlaub in den ersten drei Monaten des folgenden Kalenderjahrs gewährt und genommen werden. Kuren und Schonzeiten dürfen nicht auf den Urlaub angerechnet werden,
    soweit ein Anspruch auf Entgeltfortzahlung im Krankheitsfall (Entgeltfortzahlung) besteht.
    Während des Bestehens des Arbeitsverhältnisses gilt ein Abgeltungsverbot.

    6. Vergütung: Urlaubsentgelt, Urlaubsgeld. Erkrankt ein Arbeitnehmer während des Urlaubs, so werden die durch ärztliches Zeugnis nachgewiesenen Tage der Arbeitsunfähigkeit auf den Jahresurlaub nicht angerechnet.

    Kann der Urlaub wegen Beendigung des Arbeitsverhältnisses ganz oder teilweise nicht mehr gewährt werden, so ist er
    abzugelten. Mit Ablauf des Übertragungszeitraums wird der Arbeitgeber deren Verpflichtung zur Urlaubsgewährung frei, soweit
    er nicht die Unmöglichkeit der Urlaubsgewährung zu vertreten hat.
    Hat der Arbeitnehmer im laufenden Urlaubsjahr nur einen Teilanspruch wegen nicht erfüllter Wartezeit,
    so ist dieser Urlaub auf bestellung des Arbeitnehmers
    auf Gesamteindruck nächste Urlaubsjahr zu übertragen und damit Urlaub des folgenden Jahres zu gewähren.

  21. 과유불급表示:

    Thanks for ones marvelous posting! I actually enjoyed
    reading it, you will be a great author.I
    will ensure that I bookmark your blog and will eventually come
    back in the future. I want to encourage you continue your
    great job, have a nice evening!

  22. always i used to read smaller articles that as well clear their motive,
    and that is also happening with this piece of writing which I am reading here.

  23. Hola! I’ve been following your weblog for a long time now and
    finally got the courage to go ahead and give you a shout
    out from Kingwood Tx! Just wanted to tell you keep up the great job!

  24. Hi, 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 feedback? If so how do you prevent 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.

  25. I know this if off topic but I’m looking into starting my own weblog and was wondering what all is needed to get setup?
    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
    recommendations or advice would be greatly appreciated. Many
    thanks

  26. pbase.com表示:

    It’s going to be ending of mine day, but before end
    I am reading this great piece of writing to increase my experience.

  27. Good article! We are linking to this great article on our site.
    Keep up the great writing.

  28. twitter.com表示:

    If some one wishes expert view concerning running a blog then i
    suggest him/her to pay a visit this web site, Keep up the pleasant job.

  29. discuss表示:

    Good day! This is my first visit to your blog! We are a group of volunteers and starting
    a new initiative in a community in the same niche.

    Your blog provided us beneficial information to work on. You
    have done a marvellous job!

  30. Hello there! Do you know if they make any plugins to assist with SEO?
    I’m trying to get my blog to rank for some targeted
    keywords but I’m not seeing very good gains. If you know of any
    please share. Many thanks!

發佈留言

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