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,252,301 Responses

  1. Hello there! I could have sworn I’ve been to this web site before but after browsing through some of
    the articles I realized it’s new to me. Nonetheless, I’m
    certainly delighted I found it and I’ll be book-marking it and checking back regularly!

  2. Hi there very cool site!! Man .. Excellent .. Wonderful ..
    I will bookmark your site and take the feeds also? I am satisfied to search out
    so many helpful information here in the publish,
    we need work out more strategies on this regard, thank you for sharing.
    . . . . .

  3. autohub.ng表示:

    I’ve been browsing on-line more than three hours nowadays,
    yet I never discovered any fascinating article like yours.
    It’s beautiful worth sufficient for me. In my view, if all site owners and bloggers made excellent content material as you
    probably did, the web will probably be much more
    helpful than ever before.

  4. My relatives all the time say that I am wasting my time here at web, however I know I am getting
    familiarity everyday by reading such pleasant articles or reviews.

  5. Ahaa, its pleasant discussion concerning this article here
    at this weblog, I have read all that, so at this time me also commenting at this place.

  6. No matter if some one searches for his required thing, therefore
    he/she needs to be available that in detail, so that thing is maintained over here.

  7. Respect to op, some fantastic information.

  8. madusamawa表示:

    Hi, i think that i saw you visited my web site
    thus i came to “return the favor”.I’m trying to find things to improve my website!I suppose its ok to use some of your ideas!!

  9. May I simply just say what a comfort to discover somebody who
    really knows what they’re discussing over the internet.
    You definitely realize how to bring an issue to light and make it important.

    More people ought to read this and understand this side of the
    story. I was surprised that you aren’t more popular because
    you certainly have the gift.

  10. Dazu schneiden Sie eine der Fräse vorsichtig zwischen Mauer und Fensterrahmen lang.
    Denken Sie dabei daran, dass die Ankerpratzen aus Metall mit einer Metalltrennscheibe geschnitten werden müssen.
    Möglicherweise, wie stark Sie dem Mauerwerk zusetzen mussten, ist es nun vor allem notwendig,
    eine glatte Fläche für den Einbau der neuen Fenster erreichbar.
    Sitzen: Den Spachtel trocknen lassen, bevor es weiter geht.
    Wie lange dieser aushärten muss, können Sie den Herstellerangaben entnehmen. Dies geht am einfachsten, wenn
    Sie eventuell entstandene Lücken mit Spachtelmasse ausgleichen. Die Schritte,
    die wir vorher ausgefressen haben, müssen nun in umgekehrter Reihenfolge wiederholt werden. Nach befestigen Sie das
    Dekompressionsdichtband außen am Fensterrahmen. Wir fangen damit Fensterrahmen an. Dazu müssen die
    Fensterflügel wie oben beschrieben entfernt werden. Mit „außen” sind die Kanten gemeint, die später gen Fenstersturz und Fensterlaibungen zeigen werden.
    Das Dekompressionsdichtband dehnt sich Richtung
    Wand aus und sorgt später für eine gute
    Abdichtung. Auch Fenster 3 fach Verglasung finden Sie hier zu Lande.

  11. Great weblog right here! Also your web site loads up fast!
    What host are you using? Can I get your affiliate hyperlink in your host?
    I wish my site loaded up as quickly as yours lol.

  12. Hi, for all time i used to check blog posts here in the early hours in the daylight,
    for the reason that i enjoy to gain knowledge of more and more.

  13. Hello, after reading this awesome paragraph i
    am too glad to share my knowledge here with mates.

  14. Thanks to my father who told me concerning this web site, this weblog is truly amazing.

  15. obviously like your web-site but you need to check the spelling on quite a few of your posts.
    Several of them are rife with spelling issues and I in finding it very troublesome to
    inform the truth nevertheless I’ll definitely
    come again again.

  16. Pretty! This has been a really wonderful post. Thank you for providing these details.

  17. slot pulsa xl表示:

    You made some decent points there. I checked on the internet for more info
    about the issue and found most individuals will go along with your views
    on this web site.

  18. einbaufenster表示:

    Unsere Kunden profitieren beim Fenster kaufen von einigen Vorteilen. Sie erhalten Qualität Made in Germany zu fairen Konditionen und bei Großbestellungen mit einem
    adäquaten Rabatt. Ohne lange Wartezeiten liefern wir zuverlässig, sowie ohne zusätzliche Versandkosten an Sie
    aus. Sie können in unserem Fensterkonfigurator außerdem Profilsysteme reich an Dekorfolien wählen.
    Wir fertigen hochwertige Energiesparfenster aus Fensterprofilen von Kömmerling
    und Aluplast. Gerne erhalten auch auf Bitte ein Angebot zu
    Alu Fenstern. In verschiedenen Farben und Holzoptiken stellen Sie sich so Ihr Wunschfenster zusammen.
    Wenn Sie neue Fenster benötigen, können Sie auch ungewöhnliche Maße
    bei uns konfigurieren. Auf Ihre Bestellung müssen Sie kurze
    fuffzehn machen, da wir selbst PVC-Fenster mit Dekor innerhalb von sechs Wochen ausliefern und Ihnen sowohl die Bezahlung per Vorkasse mit Skonto, als
    auch den Rechnungskauf versichern. Außerdem vermitteln wir Montagedienstleister,
    die ihr Wissen, wie es gemacht wird und deren Sie Ihre neuen Fenster und
    Türen professionell einbauen ganz sicher sein. Alle Materialien wie spezielle
    Verglasungen zum Schallschutz zum konfigurieren von schalldichten Fenstern, Einbruchschutz Fenster mit besonderen Beschlägen oder Fensterzubehör
    können Sie mit wenigen Klicks auswählen. Im Fensterkonfigurator stellen Sie Ihr Wunschfenster zusammen. Probieren Sie es aus!
    Sie haben noch Fragen? Nutzen Sie unseren Rückrufbutton. Wir
    beraten Sie gerne.

  19. Hey very nice blog!

  20. What’s up to all, the contents present at this web page are really remarkable for people experience, well, keep up the good
    work fellows.

  21. When someone writes an piece of writing he/she maintains the image of a user in his/her
    brain that how a user can be aware of it. So that’s why this post
    is perfect. Thanks!

  22. If some one wishes to be updated with latest technologies after that he must be visit this
    site and be up to date daily.

  23. I truly treasure your work, Great post.

  24. I was wondering if you ever considered changing the page layout of your website?
    Its very well written; I love what youve got to say. But maybe you could
    a little more in the way of content so people could connect with it better.
    Youve got an awful lot of text for only having 1 or two pictures.
    Maybe you could space it out better?

  25. Roseanne表示:

    I like the valuable information you provide in your articles.
    I will bookmark your weblog and check again here frequently.
    I’m quite certain I will learn many new stuff right here!
    Best of luck for the next!

  26. Hi there would you mind sharing which blog platform you’re working with?
    I’m looking to start my own blog in the near future but I’m having
    a tough time choosing between BlogEngine/Wordpress/B2evolution and Drupal.
    The reason I ask is because your design and style seems different then most
    blogs and I’m looking for something unique.
    P.S My apologies for being off-topic but I had to
    ask!

  27. türkçe yama表示:

    Türkçe Yama
    Türkiye’nin en kaliteli içeriğine sahip olan turkce-yama.net,
    güncel oyunları ve APK’ları sisteminde barındırmaktadır.
    Kaliteli içeriklerin paylaşıldığı Türkçe yama da tüm indirmeler tamamen ücretsiz sizlerin hizmetinizdedir.
    Türkçe yama ile ilgili kendi kadrosuyla sunmuş olduğu hizmetler siz değerli ziyaretlerimiz sayesinde daha iyi
    yerlerde gelecektir.

  28. Hi to every one, the contents existing at this website are actually awesome for people experience, well, keep up the nice work fellows.

  29. Please let me know if you’re looking for a article writer for your site.

    You have some really good posts and I think I would be a good asset.

    If you ever want to take some of the load off,
    I’d really like to write some articles for your blog in exchange for a link back to mine.

    Please blast me an email if interested. Thanks!

  30. slot online表示:

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

發佈留言

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