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,245,145 Responses

  1. BrandenSlomy表示:

    priligy: priligy maxpharm – cheap priligy

  2. Oh my goodness! Incredible article dude! Thanks, However I am
    going through troubles with your RSS. I don’t know why
    I am unable to subscribe to it. Is there anybody else
    getting similar RSS problems? Anyone that knows
    the answer will you kindly respond? Thanks!!

  3. This article presents clear idea designed for the new users of blogging, that really how
    to do blogging.

  4. Nikefut表示:

    dark market list dark market list blackweb

  5. BrandenSlomy表示:

    max pharm: priligy max pharm – priligy maxpharm

  6. BrandenSlomy表示:

    can i purchase cheap clomid without insurance: clomid – how to buy cheap clomid prices

  7. Quantum Xrift表示:

    Hi friends, good paragraph and pleasant arguments commented at this place, I am really enjoying
    by these.

  8. Узнай все о варикоцеле симптомы варикоцеле у мужчин симптомы

  9. Ripple Energy表示:

    Hello there, I found your website by way of Google whilst looking for a similar subject, your
    site came up, it seems to be great. I’ve bookmarked it in my google bookmarks.

    Hello there, simply was aware of your weblog through Google, and
    located that it is truly informative. I am going to watch out for brussels.

    I’ll appreciate if you happen to continue this in future.

    Numerous other folks will be benefited out of your writing.
    Cheers!

  10. Узнай все о чем опасно варикоцеле лапароскопия варикоцеле

  11. If you wish for to grow your knowledge just keep visiting this website and be updated with the latest news posted here.

  12. Dereketerm表示:

    prednisone 20 mg generic: prednisoneraypharm – buy prednisone canadian pharmacy

  13. StevenNub表示:

    cost clomid without a prescription: clomid rex pharm – where to get generic clomid online

  14. BrandenSlomy表示:

    where can i buy generic clomid pills: clomid – how to buy generic clomid no prescription

  15. Markdob表示:

    Приветствую. Подскажите, где почитатьразные блоги о недвижимости? Пока нашел – https://credomir.ru

  16. Markdob表示:

    Всем привет! Может кто знает, где найтиполезные статьи о недвижимости? Сейчас читаю – https://credomir.ru

  17. BrandenSlomy表示:

    how can i get clomid prices: clomid rex pharm – where to buy cheap clomid pill

  18. Great article! That is the kind of info that should be shared
    across the web. Shame on the search engines for no longer positioning this publish higher!
    Come on over and seek advice from my website . Thanks =)

  19. toto12表示:

    I all the time emailed this webpage post page to all my associates, as if like to read
    it afterward my contacts will too.

  20. Markdob表示:

    Всем привет! Может кто знает, где найтиполезные блоги о недвижимости? Сейчас читаю – https://credomir.ru

  21. Markdob表示:

    Всем привет! Может кто знает, где почитатьразные блоги о недвижимости? Сейчас читаю – https://credomir.ru

  22. Its like you read my thoughts! You seem to grasp so much approximately this, like you wrote the book in it or something.
    I feel that you just could do with a few % to pressure the message house a
    bit, however instead of that, that is excellent blog. An excellent read.
    I’ll definitely be back.

  23. bokep indo表示:

    hello there and thank you for your info – I’ve certainly picked up anything new from right here.

    I did however expertise a few technical points using this website, since I experienced to reload the web site a lot
    of times previous to I could get it to load correctly.
    I had been wondering if your web hosting is OK? Not that I’m complaining,
    but sluggish loading instances times will sometimes affect
    your placement in google and can damage your quality score if advertising and marketing with
    Adwords. Well I’m adding this RSS to my e-mail and can look out for much more of your
    respective exciting content. Ensure that you update this again soon.

  24. Lazrdkc表示:

    Пошаговая инструкция по официальной покупке диплома о высшем образовании

    blogsfere.com/viewtopic.php?t=203891

發佈留言

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