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

868,404 Responses

  1. It’s an amazing article designed for all the online
    viewers; they will obtain benefit from it I am sure.

  2. discuss表示:

    Sweet blog! I found it while browsing on Yahoo News. Do you have any tips on how
    to get listed in Yahoo News? I’ve been trying for a while
    but I never seem to get there! Thank you

  3. Woah! I’m really digging the template/theme of this site.

    It’s simple, yet effective. A lot of times it’s difficult to get that “perfect balance” between user friendliness and appearance.
    I must say you have done a great job with this.

    Additionally, the blog loads extremely fast for me on Opera.
    Superb Blog!

  4. Hi there, just became alert to your blog through Google, and found
    that it’s truly informative. I’m going to watch out for brussels.
    I’ll be grateful if you continue this in future. Many people will be benefited from your
    writing. Cheers!

  5. nordic walkng表示:

    Wenn Sie mit Sportart erfahren sind und auch längere Touren walken wollen, dann können Marathonschuhe eine gute Alternative sein. Denn diese sind leicht, unterstützen das Abrollen und sind nur schwach gedämpft.
    Auch mit Trail-Laufschuhen können Sie normalerweise gut im Gelände walken. Bei der Auswahl
    der passenden Nordic-Walking-Schuhe müssen Sie einige
    wichtige Dinge bei der Schuhkonstruktion beachten, damit Sie lange Freude an ihnen haben. Auch Nordic-Walking-Schuhe können unterschiedlich geschnitten sein. Überprüfen Sie,
    ob die gewählte Leistenform zu Ihrer Fußform passt. Beim geraden Leisten ist
    die Fußinnenseite gerade durchgezogen, sodass er die
    natürliche Längswölbung nicht widerspiegelt. Der gebogene Leisten dagegen ist der natürlichen Fußform am besten nachempfunden. Gebogene Leisten bieten vor allem auf der Außenseite ausreichend Stützfläche.
    Die vergrößerte Stützfläche erleichtert den Ausgleich
    bei Fußfehlstellungen und bei höherem Körpergewicht.

    Für den Walker mit gesunden Füßen und einer guten Walkingtechnik ist der
    gebogene Leisten daher ideal. Eine Zwischenstufe ist der halbgebogene Leisten, der auf der Innenseite mehr Stabilität als beim gebogenen Leisten bietet.

  6. I am sure this paragraph has touched all the internet visitors,
    its really really fastidious article on building up new webpage.

  7. Good day! I just want to offer you a big thumbs up for the great information you have here on this post.
    I will be coming back to your blog for more soon.

  8. nordic walkng表示:

    Nordic walking hat sich die letzten Jahren, auch dank moderner Materialien für die Walking Stöcke, als Trendsport etabliert.

    Hierbei Einsatz von Stöcken wird zusätzlich die Muskulatur des Oberkörpers beansprucht.
    Der Ausdauereffekt dieser Sportart und die Möglichkeit Sport im grünen, aber auch in den städten unschwer realisieren zu können, haben hierzu
    beigetragen. Sportart ist für ambitionierte Sportler ebenso geeignet wie für untrainierte Menschen. Die Gelenke werden jedoch stärker belastet als beim normalem Spazieren. 5%
    höher als beim konventionellen Walking, wenn dieses ohne zusätzliche Oberkörperbewegungen durchgeführt wird.
    Nach einer Studie von Sportmedizinern des Krankenhauses für Sportverletzte
    in Hellersen ist der Sauerstoffverbrauch und daraus folgernd die Ausdauerbelastung beim Nordic walking mit korrekter Ausführung ca.
    Sportart ist eine Sportart mit zyklischem Bewegungsablauf,
    wobei der rechte Stock immer dann Bodenberührung hat, wenn politische Kraft Ferse aufsetzt und der linke Stock, wenn die rechte Ferse aufsetzt.
    Die Stöcke werden nah am Körper geführt.

  9. certainly like your web site however you have to take a look at
    the spelling on several of your posts. A number of them are rife
    with spelling problems and I find it very bothersome
    to tell the reality however I’ll certainly come back again.

  10. discuss表示:

    Very nice article, exactly what I needed.

  11. Touche. Sound arguments. Keep up the amazing spirit.

  12. My partner and I stumbled over here from a different web page and thought I should check things out.
    I like what I see so i am just following you. Look forward
    to looking into your web page again.

  13. Demnach gestalten Sie mit gutem Conent, wozu auch Bilder und Videos
    zählen, nicht ein einsamer optisch ansprechende Seite sondern stellen den Website-Besuchern auch Mehrwert und interessante Informationen zur Verfügung.
    Dabei gilt: Schreiben Sie Ihre Inhalte für die Nutzer und nicht für
    die Suchmaschine, wie es früher war. Da Google das User-Verhalten als wichtigen Faktor fürs Ranking
    in den Suchergebnissen zählt, ist die Optimierung der Anwendererlebnis ein ausschlaggebender Faktor.
    Eine Website mit Usability erreicht eine längere Aufenthaltsdauer bei Nutzern, sowie mehr Seitenaufrufe pro Benutzer.
    Die Benutzerfreundlichkeit einer Website, Usability genannt, ist
    ein ausschlaggebender Faktor für die Platzierung in den Suchmaschinen. Natürlich
    spielt für diese Aspekte ebenfalls guter Content
    eine Rolle. Wenn User mit der Usability und den angebotenen Informationen zufrieden sind, kommen Sie auch wieder.
    Zur Usability zählt erst recht die Effizienz der Website.
    Erreichen Nutzer ihre Ziele, wenn Sie die Seite besuchen? Nur wenn
    Besucher sich problemlos auf der Website bewegen können und
    finden was sie suchen, sind sie auch zufrieden und diese Zufriedenheit
    wirkt sich aufs Google-Ranking aus. Jede Seite auf der Homepage sollte über einen SEO-Titel, bzw.
    Seitentitel, verfügen, der zum Inhalt passt.

  14. adfoc.us表示:

    After I originally commented I seem to have clicked the -Notify me when new comments
    are added- checkbox and now whenever a comment is added I
    get four emails with the exact same comment.
    Is there an easy method you are able to remove me from that service?

    Thanks!

  15. Howdy! This post couldn’t be written any better! Reading this post reminds me of my old room mate!
    He always kept talking about this. I will forward
    this write-up to him. Pretty sure he will have a good read.
    Many thanks for sharing!

  16. Hi there! 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 valuable information to work on. You have done a
    extraordinary job!

  17. I was able to find good advice from your articles.

  18. What’s up friends, its enormous piece of writing regarding educationand completely explained, keep it up all the
    time.

  19. Hi, I read your new stuff on a regular basis. Your story-telling style is awesome,
    keep doing what you’re doing!

  20. Tania表示:

    Ahaa, its good dialogue on the topic of this
    paragraph here at this weblog, I have read all that,
    so now me also commenting at this place.

  21. You could certainly see your skills in the work you write.
    The world hopes for even more passionate writers such as
    you who aren’t afraid to mention how they believe. Always go after your heart.

  22. I’m really enjoying the design and layout of your site.
    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 developer to create your theme? Fantastic work!

  23. I have read several just right stuff here. Certainly worth
    bookmarking for revisiting. I surprise how so much effort you set to make
    this kind of fantastic informative web site.

  24. Der Hersteller Ecco gehört zu den führenden Anbietern von Sportart Schuhen für
    Männer und Frauen. Dieses Modell besteht aus 100 Prozent
    Leder, das Innenmaterial ist aus Textilstoff, die Sohle aus Kunststoff.
    Die Modelle sind allesamt auf die besonderen Bedürfnisse
    bei der Ausdauersportart abgestimmt. Auch diese Schuhe können fest mit
    Schnürsenkeln verschlossen werden. Ausgezeichnet ist die Passgenauigkeit, denn die Größen dieser Nordic Walking Schuhe Herren fallen regulär aus.
    Ein weiterer Vorteil dieser Schuhe ist die Wasserdichte.
    Ecco hat bei diesem Modell Nordic Walking Schuhe Herren wieder alles
    getoppt. Die Schuhe sind praktisch, bequem und das Preis-Leistungsverhältnis stimmt komplett.
    Besonders gelobt wurden diese Nordic Walking Schuhe Herren wegen ihrer sehr guten Verarbeitung, der Robustheit sowie dem sehr bequemen Tragekomfort – auch auf schwierigem Untergrund und für
    längere Touren. Zudem ist er optisch so gestaltet, dass er auch wie ein Glöckerl und von den Käufern sehr genießen auch als normaler Freizeitschuh oder sogar im
    Büro getragen werden kann. Die Fersen sind in diesen Schuhen sehr weich gepolstert, was den Tragekomfort noch erhöht.
    Auch das eingearbeitete Fußbett dieser Nordic Walking Schuhe Herren hat
    sehr gute Bewertungen erhalten. Es gibt so konzipiert, dass es sich jedem Fuß ideal anpasst.

  25. Hi I am so glad I found your site, I really found you
    by error, while I was researching on Yahoo for something else, Nonetheless I am here now and would just like to
    say thanks for a fantastic post and a all round entertaining blog (I also love the theme/design), I don’t have
    time to read 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
    much more, Please do keep up the great work.

  26. Heya this is kind of of off topic but I was wanting to know if blogs use WYSIWYG editors or if you have
    to manually code with HTML. I’m starting a blog soon but have no coding experience so I wanted to get advice from someone with experience.
    Any help would be greatly appreciated!

  27. At this moment I am going to do my breakfast, after having my breakfast coming over again to read more news.

  28. Hello! I could have sworn I’ve been to this blog before but
    after checking through some of the post I realized it’s new to me.
    Anyways, I’m definitely happy I found it and I’ll be
    bookmarking and checking back often!

  29. Good day! This is my first comment here so I just wanted to give a quick shout out and tell you I truly enjoy reading your
    blog posts. Can you suggest any other blogs/websites/forums that cover
    the same topics? Thanks a lot!

發佈留言

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