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,251,801 Responses

  1. you are truly a excellent webmaster. The web site loading pace is incredible.
    It seems that you’re doing any unique trick. In addition, The contents
    are masterwork. you have performed a fantastic activity on this topic!

  2. king-wifi.win表示:

    Greetings! Very helpful advice in this particular article!
    It is the little changes which will make the most significant changes.
    Thanks for sharing!

  3. This is my first time pay a quick visit at here and i am actually pleassant to read all at single place.

  4. Hi everyone, it’s my first pay a quick visit at this web page, and paragraph is truly fruitful in support of me, keep up posting these types of articles or reviews.

  5. sauger表示:

    In unserem Fall mit einem überschaubaren 3-Zimmer Erdgeschoss waren das über 2,5 Stunden in zwei Fahrten. Flur übersehen, obwohl die Basis direkt neben der Flur-Tür stand.
    Der Tank des Roboters ist kinderleicht zu entnehmen und aus zu kippen.
    Allerdings ist die Box nicht auslaufsicher.
    Er befindet sich unterm Deckel des Roboters im
    zentrum. Die größten Nachteile sind in unseren Augen die Lautstärke und die Notwendigkeit von Licht.
    Nächtliches Staubsaugen ist ausgeschlossen, es sei denn die Räume sind beleuchtet.

    Wer den Roboter ins Obergeschoß trägt, dem kann herausrieselnder Sand begegnen. Die Lautstärke hat eine ratternde Charakteristik, ähnlich
    dem Neato D701. Allerdings rumpelt es beim Fahren nicht unbedingt stark wie beim Neato,
    das »Fahrwerk« des iRobot scheint besser abgefedert. Für
    deutlich weniger gibt es auch gute Absaugstation-Geräte
    von welcher Konkurrenz: Deebot Ozmo T8 AIVI, unsere Empfehlung bei den Wischrobotern (Kombigerät Saugen und Wischen).
    Absaug-Basis für deutlich weniger unbemannt ist. Der Dreame L10 Pro (Sub Brand von Xiaomi) kommt
    mit einem großen Staubtank von 570 Millilitern und
    einem einfachen Wischkonzept daher: Der Staubtank sitzt im Saugroboter,
    die Wischplatte mit Wischtank (300 ml) wird auf Kommando einfach untergeschoben.

  6. This paragraph will assist the internet visitors for building
    up new web site or even a blog from start to end.

  7. After looking into a few of the articles on your site, I honestly appreciate your technique of writing a blog.
    I added it to my bookmark website list and will be checking
    back in the near future. Take a look at my website too
    and let me know what you think.

  8. critical review. Additionally visit that site to attempt game slot online.
    Amazing web page has received reputation from slot pulsa online playing clients in Negara sendiri.

    Generally there are usually a few exciting promos should you join at this time.

  9. Greetings! Quick question that’s totally off topic. Do you know how to make your site mobile
    friendly? My weblog looks weird when viewing from my iphone.
    I’m trying to find a template or plugin that might be able to correct this
    issue. If you have any suggestions, please share.
    With thanks!

  10. discuss表示:

    Asking questions are in fact good thing if you are not understanding something fully, however this post offers
    fastidious understanding even.

  11. I am truly grateful to the owner of this site who has shared this enormous post at
    at this time.

  12. Good post. I’m going through some of these issues as
    well..

  13. vimeo.com表示:

    Thank you for sharing your thoughts. I truly appreciate your efforts and I
    am waiting for your further post thanks once again.

  14. It’s genuinely very difficult in this active life to listen news on TV, thus I only use the web for that purpose, and get the newest information.

  15. discuss表示:

    Everything is very open with a clear clarification of the issues.
    It was truly informative. Your site is useful. Many
    thanks for sharing!

  16. each time i used to read smaller posts which as well clear their motive, and that is also happening with
    this post which I am reading here.

  17. Key pendant表示:

    Do you have a spam problem on this website; I also am a blogger, and I
    was wanting to know your situation; we have developed some nice methods and we are looking to trade
    strategies with others, why not shoot me an e-mail if interested.

  18. Oh my goodness! Impressive article dude! Thank you, However
    I am going through troubles with your RSS. I don’t understand the reason why I cannot join it.

    Is there anybody else getting similar RSS issues? Anyone who knows the solution can you kindly respond?
    Thanks!!

  19. bonrollen表示:

    Weil man sich kaum darauf verlassen kann, nach zehn Jahren noch denselben Rechner mit derselben Festplatte in betrieb nicht liiert,
    sehr zu empfehlen die Archivierung auf einem nicht wiederbeschreibbaren Datenträger.
    Damit entfällt auch die Anforderung, verschlüsselte Dateien auf der Festplatte bisweilen gemäß Empfehlungen in der BSI-Richtlinie TR-02102 neu zu verschlüsseln. Wer eine als E-Mail-Anhang erhaltene Rechnung nur ausdruckt und abheftet, riskiert ebenfalls seinen Vorsteuerabzug und womöglich
    auch ein Bußgeld. Andernfalls geht der Gesetzgeber nämlich davon aus, dass man eine Datei,
    die Jahre zuvor die üblichen Schlüsselbreite kodiert und archiviert worden ist, mit den inzwischen verfügbaren leistungsfähigeren PCs dekodiert und manipuliert
    haben könnte. £Gelten für Privatleute dieselben Vorschriften wie für
    Geschäftsleute? ¶¢In den meisten Fällen hat man als Privatperson nicht einmal Anspruch
    auf eine förmliche Rechnung und kann Ausgaben auch mit einer bloßen Quittung oder einem Eigenbeleg
    ausüben. Wann eine elektronische Rechnung auch als Beleg in einer
    privaten Steuererklärung taugt, ist nicht klar geregelt.

  20. First off I want to say great blog! I had a quick question in which I’d like to
    ask if you do not mind. I was curious to find
    out how you center yourself and clear your mind prior to writing.
    I’ve had difficulty clearing my mind in getting my thoughts out.
    I truly do enjoy writing but it just seems like the first 10 to 15
    minutes tend to be wasted simply just trying to
    figure out how to begin. Any ideas or hints? Many thanks!

  21. tostolarz.pl表示:

    Hello, i think that i noticed you visited my weblog
    so i got here to return the desire?.I am trying to to find issues to improve my site!I assume its ok to make use
    of some of your ideas!!

  22. It’s fantastic that you are getting ideas from this paragraph as
    well as from our discussion made at this time.

  23. Hello, i think that i saw you visited my blog thus i came to “return the favor”.I’m attempting to find
    things to improve my website!I suppose its
    ok to use a few of your ideas!!

  24. Hello to every , since I am in fact keen of reading this
    web site’s post to be updated on a regular basis. It carries good material.

  25. Thanks for your marvelous posting! I seriously enjoyed
    reading it, you may be a great author.I will make certain to bookmark your blog
    and will come back later on. I want to encourage you continue your great job,
    have a nice afternoon!

  26. slot online表示:

    Hey I know this is off topic but I was wondering if
    you knew of any widgets I could add to my blog that automatically
    tweet my newest twitter updates. I’ve been looking for a plug-in like this for
    quite some time and was hoping maybe you would have some experience with something like this.
    Please let me know if you run into anything. I truly enjoy reading your blog and I look forward to your new updates.

  27. cqms.skku.edu表示:

    Pretty! This was a really wonderful article. Thanks
    for supplying these details.

  28. notes.io表示:

    I know this site offers quality depending posts and other material, is there
    any other web page which provides such things in quality?

  29. You made some good points there. I looked on the web for more
    information about the issue and found most individuals will
    go along with your views on this website.

發佈留言

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