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,368,799 Responses

  1. Nikefut表示:

    dark web search engine darknet sites darkmarket link

  2. Joshua Owen表示:

    I love how a deck can transform an outdoor space! For unique designs, visit austin deck builders

  3. KennethPah表示:

    prednisone 20mg tablets where to buy prednisone 2.5 tablet price for 15 prednisone

  4. remapping表示:

    Hi there I am so grɑteful I found your web site, I realy found you by
    error, while I was browsing on Үahoo for something else, Regardless I
    am here now and would just ⅼike to say қudos for a incгediblе post
    and a all round entertaining blog (I allso love the thеme/design), I don’t habe time tto brօwse it alll aat
    the minute but I have ƅook-marked iit and also included yⲟur RSS fеeds, sso when I have time I
    will bbe back too read much more, Please do kep սp the superb jo.

  5. Addie Parsons表示:

    Just had an aromatherapy session at a lovely Austin spa, and it was heavenly! Can’t recommend it enough! For more info, visit hydrafacial austin

  6. вывод из запоя [url=www.belbeer.borda.ru/?1-6-0-00000780-000-0-0-1730825410/]вывод из запоя[/url] .

  7. Howdy, i read your blog from time to time and i own a similar one and
    i was just curious if you get a lot of spam feedback?
    If so how do you prevent it, any plugin or anything you
    can suggest? I get so much lately it’s driving me insane so any assistance is
    very much appreciated.

  8. Baccarat Gambling – Part 1; A Fun, Simple Game Could Possibly Win Certainly!
    에볼루션 오토

  9. EdgarWat表示:

    Интересные статьи о займах – https://www.uarating.com/news/gde-vzyat-deneg-do-zarplaty/

  10. Hello to all, because I am genuinely eager of
    reading this website’s post to be updated regularly. It includes pleasant
    stuff.

  11. Sarah Byrd表示:

    For anyone hesitant about who to choose: try out #‘’$ `‘’! You won’t regret it Fresno car shippers

  12. Porn Sex表示:

    This post is truly a fastidious one it helps new the web visitors, who are wishing in favor of blogging.

  13. So delighted to see somebody discussing the advantages of soft cleaning versus pressure cleaning– excellent insights here best Conway pressure washing

  14. Nicholas Ruiz表示:

    Making sure our home prepares prior to winter season implies reaching out to professionals like ### anyKeyWord ### as soon as possible https://mint-experiment.uncrn.co/blog/selecting-the-right-commercial-roof-providers-for-your-service-requirements/

  15. I am really loving the theme/design of your blog. Do you ever
    run into any browser compatibility issues? A number of my blog audience have
    complained about my site not working correctly in Explorer
    but looks great in Chrome. Do you have any suggestions to help fix this problem?

  16. конвертер юань в тенге калькулятор .

    Платформа предлагает простой интерфейс и бесплатную конвертацию валют. Будь то тенге, рубли или юани – все расчеты происходят моментально с использованием актуальных данных.

  17. great publish, very informative. I’m wondering why the opposite specialists of this sector don’t realize this.

    You should continue your writing. I am sure, you’ve
    a huge readers’ base already!

  18. hey there and thank you for your information – I’ve certainly picked
    up something new from right here. I did however expertise some
    technical points using this web site, since I experienced to reload the web
    site a lot of times previous to I could get it to load properly.

    I had been wondering if your web host is OK? Not that I’m complaining, but slow loading instances times will often affect your
    placement in google and could damage your high quality score if ads
    and marketing with Adwords. Well I’m adding
    this RSS to my email and could look out for a lot more of your respective fascinating content.
    Ensure that you update this again soon.

  19. Thanks , I have just been looking for info approximately this topic for a long time and
    yours is the greatest I have found out so far. But,
    what about the bottom line? Are you sure concerning
    the source?

  20. Nikefut表示:

    deep web drug url dark web drug marketplace dark web link

  21. It’s an awesome post in support of all the internet visitors; they will get advantage from it I am sure. http://www.0768baby.com/comment/html/?317468.html

  22. Hello there I am so thrilled I found your blog page, I really found you by mistake, while I was looking
    on Aol for something else, Anyhow I am here now and would
    just like to say many thanks for a remarkable post and a all round exciting 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 much more, Please do keep up the fantastic work.

  23. SamuelBix表示:

    prednisone 500 mg tablet: prednisone 40 mg rx – prednisone 250 mg

發佈留言

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