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,372,445 Responses

  1. AngelCroft表示:

    предметная съемка для маркетплейсов – Услуги фотосъемки товаров для популярных маркетплейсов, таких как Ozon, Wildberries и других.

  2. Amazing things here. I am very glad to peer your article.

    Thanks a lot and I’m looking forward to contact you.
    Will you kindly drop me a mail?

    My blog … Mejor abogado penalista Barcelona

  3. OP表示:

    Dance Club OP

  4. Greetings! Very helpful advice in this particular article!
    It is the little changes that make the most important changes.
    Thanks a lot for sharing!

  5. снятие ломок на дому [url=www.dubna.myqip.ru/?1-5-0-00000291-000-0-0-1730832694]снятие ломок на дому[/url] .

  6. Ethan Graves表示:

    This is highly informative. Check out dental clinic near me for more

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

  8. CharlesNom表示:

    Photograph influences have long been cherished for their ability to capture a new spectrum of remembrances. However, individualized picture collages take this specific concept to a new new level by simply tailoring images in order to tell an distinctive, personal story. These customized collections interweave together cherished instances, making a visual narrative that resonates significantly with all the individual or perhaps group they symbolize.

    The advantage of an individual collage lies throughout its capability to suggest emotion. By thoroughly selecting photographs that will hold personal value, the collage becomes a tangible reflection regarding one’s journey, milestones, and experiences. It’s more than merely a decoration—it’s a living memory, taken in time.

    https://jaidenddqcp.blogdomago.com/25481807/unlocking-reminiscences-the-great-thing-about-individualized-photograph-collages

    In addition, individualized collages create excellent gifts, enabling recipients to relive their most treasured moments. Whether exhibited at home or workplace, these collages certainly not only offer visual appeal and also function as powerful memory joggers of the human relationships, adventures, and breakthrough that shape each of our lives.

    Ultimately, the particular great thing concerning individualized photograph collages is their capability to preserve memories in a significantly meaningful, creative approach. They transform personal snapshots into some sort of cohesive work of art, acquiring the essence involving life’s most memorable moments.

  9. 7 Tips To Make The Maximum Use Of Your Audi A1 Key Replacement Audi q7 replacement key

  10. Highly energetic post, I enjoyed that bit. Will there be a part 2?

  11. I have been exploring for a little for any high-quality articles or blog
    posts on this kind of house . Exploring in Yahoo I
    eventually stumbled upon this website. Studying this information So i’m
    satisfied to express that I’ve a very good uncanny feeling I found out exactly what I
    needed. I so much definitely will make certain to do not omit this site and
    provides it a look regularly.

  12. Just desire to say your article is as astounding. The
    clearness in your publish is simply cool and that i could suppose
    you are knowledgeable in this subject. Fine with your permission let
    me to clutch your feed to keep updated with impending post.
    Thank you 1,000,000 and please carry on the gratifying work.

  13. First of all I want to say great blog! I had a
    quick question which I’d like to ask if you do not mind.
    I was interested to know how you center yourself and clear your thoughts before
    writing. I have had a difficult time clearing my mind in getting my
    ideas out there. I truly do enjoy writing however it just seems like the
    first 10 to 15 minutes are lost simply just trying to figure
    out how to begin. Any suggestions or hints?
    Many thanks!

  14. What Are The Reasons You Should Be Focusing On Making Improvements To Asbestos Mesothelioma mesothelioma attorneys

  15. Jean Hoffman表示:

    Highlighting warranties in roofing is key—always ask about them before making a decision! roofing company

  16. CharlesNom表示:

    Photograph collages have long been cherished for their ability to capture some sort of spectrum of recollections. However, individualized photo collages take this specific concept to the new level by simply tailoring images to tell an unique, personal story. These kinds of customized collections weave together cherished times, developing a visual narrative that resonates seriously using the individual or group they signify.

    Beauty of an individual collage lies within its capability to stir up emotion. By thoroughly selecting photographs of which hold personal value, the collage becomes a tangible reflection involving one’s journey, milestones, and experiences. It’s more than merely a decoration—it’s some sort of living memory, taken in time.

    https://jaidenddqcp.blogdomago.com/25481807/unlocking-reminiscences-the-great-thing-about-individualized-photograph-collages

    In addition, individualized collages help to make excellent gifts, allowing recipients to re-experience their most cherished moments. Whether viewed at home or business office, these collages certainly not only offer cosmetic appeal and also serve as powerful reminders of the associations, adventures, and milestones that shape our own lives.

    Ultimately, the particular great thing regarding individualized photograph collages is their capability to preserve recollections in a deeply meaningful, creative way. They transform personal snapshots into some sort of cohesive work of art, taking the essence associated with life’s most unforgettable moments.

發佈留言

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