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...

864,022 Responses

  1. Hi would you mind letting me know which webhost you’re working with?
    I’ve loaded your blog in 3 completely different web browsers and I must say this blog loads a lot faster then most.
    Can you recommend a good hosting provider at a reasonable price?

    Cheers, I appreciate it!

  2. It’s a pity you don’t have a donate button! I’d without a doubt donate to
    this excellent blog! I suppose for now i’ll settle for
    book-marking and adding your RSS feed to my Google account.
    I look forward to fresh updates and will share this blog
    with my Facebook group. Talk soon!

  3. Wow, marvelous blog layout! How long have you been blogging for?

    you made blogging look easy. The overall look of your web site is fantastic, as well as the content!

  4. Solche Funktionen können beispielsweise eine
    extreme Wendigkeit, ein sehr geringes Gewicht und ein geringer Kraftaufwand,
    um sich fortzubewegen sein. Wenn der Alltag nimmer selbständig bewältigt werden kann und auch Transfers und Sitzkorrekturen mehrere durchgeführt
    werden können, kommt ein Pflegerollstuhl zum Einsatz.
    Sowohl Fuss-, Arm- als auch die Kopfstütze lassen sich verstellen und eine Kippfunktion verändert den Sitzwinkel.
    Diese bieten höchsten Komfort, sind adipös darauf ausgelegt, dass eine Person viele
    Stunden bequem in ihm verbringen kann. Durch Verstellen der Rückenlehne kann
    sogar eine liegende Position hergestellt werden. Das Leben trotz körperlicher
    Einschränkungen in vollen Zügen zu geniessen ermöglicht ein Elektrorollstuhl.
    Zur Untermauerung der schiebenden Person kann ein Elektromotor ergänzt werden. Ein hoher Sitzkomfort und viele Einstellungsmöglichkeiten werden ergänzt durch die elektrische Steuerung.
    Ein Steuerungsmodul ist in die Armlehne integriert und ermöglicht es, mit einer Hand ohne grossen Aufwand, den Rollstuhl in alle Richtungen zu bewegen.
    Auch die Geschwindigkeit lässt sich regulieren. Setzen Sie sich mit uns in Verbindung
    und wir finden gemeinsam heraus, welches Modell das passende für Ihre Bedürfnisse ist.

    Wenn ein Kauf als erstes nicht in Frage kommt, besteht auch die Möglichkeit, einen Rollstuhl zu mieten. Wir beraten Sie gerne!

  5. Wonderful beat ! I wish to apprentice whilst you amend your site,
    how can i subscribe for a weblog website? The account aided me a acceptable
    deal. I were a little bit acquainted of this your broadcast provided brilliant transparent concept

  6. Arbeitet der Tätowierer nachlässig, entstehen blasse und dunkle Ränder wie beim flächigen Malen mit Filzstiften. Obwohl
    die Motive künstlerisch nicht sehr komplex sind, solltest Du das Stechen von Blackout-Tattoos
    nur Profis überlassen. Einige Tätowierer sind selbst Fans des stylischen Trends und haben sich auf Blackout-Tattoos und geometrische Muster spezialisiert.

    Für ein Blackout-Tattoo musst Du also unter Umständen temporär den Tätowierer wechseln. Künstler mit Erfahrung passen Blackout-Tattoos ästhetisch an die natürliche Körperform an, damit das Ergebnis dem Auge schmeichelt.
    Andere wiederum finden schwarze Flächen unkreativ
    und widmen sich lieber bunten Motiven. Zur Verdeckung von unliebsamen Jugendsünden sind Blackout-Tattoos in manchen Fällen sinnvoll.
    Nicht alle Tattoos sind jedoch für ein Blackout Cover-up geeignet:
    Ist die Haut vernarbt oder wurden minderwertige
    Farben genutzt, sind die alten Konturen oft auch trotz Cover-up noch erkennbar und nehmen dem Tattoo
    seine Gleichmäßigkeit. Verblasste Tattoos und Aquarell-Motive
    ohne Konturen lassen sich leichter schwärzen und verschwinden komplett unter der schwarzen Tattoo-Farbe.
    Ein umstrittener Stil Ein Blackout-Tattoo lässt eine gewisse Anti-Haltung mitschwingen. Sowohl tätowierte als
    auch nicht-tätowierte Menschen finden die Körperverschönerung
    ohne konkrete Aussage oft befremdlich und etwas
    unheimlich, besonders wenn große Körperpartien mit Blackout-Mustern bedeckt
    sind oder gänzlich schwarz erscheinen. Generell bringt ein Blackout-Tattoo die gleichen Risiken mit
    sich, wie ein normales Tattoo auch. Die eine oder andere dumme Frage oder hochgezogene Augenbraue musst Du Dir also
    in fast jeder Umgebung gefallen lassen – manchmal macht gerade das
    aber auch den Reiz am Schwärzen aus. Da die Haut großflächig angegriffen wird, fallen Abwehrreaktionen des Körpers stärker
    aus als nach dem Stechen kleinerer Motive. Angesichts der großen Menge an Farbe, die
    unter Deine Haut injiziert wird, solltest Du vor dem Stechen unbedingt die Inhaltsstoffe überprüfen und Dir die Unbedenklichkeit der Farbe bestätigen lassen.
    Viele Schwarz-Töne in der Tattoo-Branche enthalten PAK-Farben,
    die aus Rußpartikeln gewonnen werden und krebserregende Kohlenstoffe
    enthalten können.

  7. Its like you read my mind! You seem to know so
    much about this, like you wrote the book in it or something.
    I think that you could do with some pics to drive the message
    home a little bit, but instead of that, this is fantastic blog.

    An excellent read. I’ll definitely be back.

  8. cutt.ly表示:

    Write more, thats all I have to say. Literally, it
    seems as though you relied on the video to make your point.
    You clearly know what youre talking about, why waste your intelligence on just posting videos to your weblog when you could be giving us something enlightening to read?

  9. It’s remarkable to go to see this web site and reading the views
    of all mates about this post, while I am also eager of getting experience.

  10. anotepad.com表示:

    Its such as you learn my mind! You seem to grasp so much about
    this, such as you wrote the book in it or something. I believe that you just can do with
    a few percent to drive the message house a bit, but instead of that, this is wonderful
    blog. An excellent read. I will certainly be back.

  11. Hi there all, here every one is sharing these kinds of familiarity, so it’s nice to read this weblog, and I used to
    pay a visit this weblog all the time.

  12. Good day! I simply wish to give you a big thumbs up for the
    excellent info you’ve got right here on this post. I am coming back to your website for more soon.

  13. Hi, I do believe this is an excellent site. I stumbledupon it 😉 I may come back once again since i have book-marked it.
    Money and freedom is the best way to change, may you be
    rich and continue to guide other people.

  14. Welche SEO-Tools nehmen wir, wo ist auch die Datenbasis gut?
    Damit beschäftigst du dich ja ganz gleich. Auf was greifen diese
    Tools eigentlich zurück? Liefern die brauchbare Ergebnisse und, ja, können wir
    da systematisch Keywords für recherchieren und aufarbeiten? Ist sehr wichtig bei der Tool-Auswahl, weil die Tools eine unterschiedliche Datenbasis haben, kommt, in welchen Ländern man ist, ne.

    F: Genau. Also alleine als Beispiel jetzt: Welchen Markt möchte ich bespielen? Und das ist natürlich schwierig
    zu unterscheiden und zu differenzieren und da eine Auswahl zu treffen. Und
    die Tools kosten halt auch Geld, ne, also gut ist auch oft eine Scheu da, dafür
    erstmal ein Budget frei realisierbar. Nicht ausbleiben Tools, die sind für den deutschen Raum total klasse,
    total super, aber viele Unternehmen sind halt international unterwegs und da braucht man andere Tools, die dann bessere Daten liefern. Also da ist viel Unsicherheit auch oft da,
    ja. Genau, das ist das eine. Man weiß auch noch überhaupt nicht
    genau, was das Tool einem dann bringt. Aber aus diesen Keywords entwickelt sich dann ja auch eine Architektur für die
    Webseite, oder?

  15. Peculiar article, just what I was looking for.

  16. discuss表示:

    Nice post. I was checking constantly this weblog and I am
    inspired! Extremely helpful info specifically the closing phase :
    ) I deal with such info much. I was looking for this certain information for a long time.
    Thanks and good luck.

  17. What i don’t realize is in fact how you’re not really much
    more neatly-favored than you may be right now.
    You are so intelligent. You recognize thus significantly
    relating to this matter, made me individually consider it
    from so many various angles. Its like women and
    men don’t seem to be involved except it’s something to do with Lady gaga!

    Your individual stuffs outstanding. At all
    times handle it up!

  18. My brother recommended I might like this web site. He was totally right.
    This post truly made my day. You cann’t imagine simply how
    much time I had spent for this information! Thanks!

  19. Hello I am so thrilled I found your blog page, I really found you by error, while I was looking on Askjeeve for something else, Regardless I am here now and would just like to
    say thanks for a marvelous 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 minute but I have bookmarked it and also included your RSS feeds, so
    when I have time I will be back to read more, Please do keep up
    the fantastic b.

  20. sc.sie.gov.hk表示:

    Hey this is kind of of off topic but I was wondering if blogs use WYSIWYG editors
    or if you have to manually code with HTML. I’m starting
    a blog soon but have no coding expertise so I wanted to get advice from someone with experience.

    Any help would be enormously appreciated!

  21. Hi there i am kavin, its my first time to
    commenting anywhere, when i read this piece of writing i thought i could
    also create comment due to this good article.

  22. Whaat i do noot understood is if truth be told how you’re now nott really
    a lot mopre well-favored than youu might be now. You’re so intelligent.
    You recognize therefore considerably on the subject
    of this matter,produced me for my part imagine itt from so many varied angles.
    Its like women and men are not fascinated unless it iss one thiing to accomplish with Woman gaga!
    Your individual stuffs outstanding. Alll the time handle it
    up!

    Also visit my homepage; reallifecam, real life cam, reallife cam, reallifecam, voyeur-house

  23. First of all I want to say superb blog! I had a quick question which I’d like to ask if you
    don’t mind. I was curious to find out how you center yourself and clear your
    mind prior to writing. I’ve had a hard time clearing my mind in getting my thoughts out.
    I truly do take pleasure in writing but it just seems like
    the first 10 to 15 minutes are usually wasted just trying to figure out how to begin. Any suggestions or hints?
    Thanks!

  24. Wow, that’s what I was searching for, what a material!
    present here at this weblog, thanks admin of this web page.

  25. telegra.ph表示:

    I will right away take hold of your rss as I can not to find your e-mail subscription hyperlink or e-newsletter service.
    Do you have any? Please permit me recognise so that I could subscribe.
    Thanks.

  26. Quality articles is the main to interest the viewers to visit the web page, that’s what this website is providing.

  27. Greetings! Very useful advice within this article! It’s the little changes which will make the biggest changes.
    Many thanks for sharing!

  28. Hi there! Would you mind if I share your blog with my zynga group?

    There’s a lot of people that I think would really
    appreciate your content. Please let me know. Many thanks

  29. It’s an awesome post designed for all the internet visitors; they will get advantage from
    it I am sure.

發佈留言

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