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,246,943 Responses

  1. AlbertDuM表示:

    minocycline 100mg over the counter: cheapest Ivermectin – minocycline cost

  2. Hello my family member! I want to say that this article is awesome,
    nice written and come with approximately all important infos.
    I’d like to peer more posts like this .

  3. Ovisfr表示:

    гѓ—гѓ¬гѓ‰гѓ‹гѓі её‚иІ© гЃЉгЃ™гЃ™г‚Ѓ – イソトレチノイン гЃЉгЃ™гЃ™г‚Ѓ イソトレチノイン処方

  4. Sazrogi表示:

    Удивительно, но купить диплом кандидата наук оказалось не так сложно
    gadjetforyou.ru/kupit-diplom-byistryiy-put-k-uspehu-v-karere

  5. Виртуальные номера телефонов для этого СМС от нашего ресурса доступны не одним лишь в нашей стране, сколько в каждой другой уголке.

    My web blog https://mybiysk.ru/business/prichiny-ispolzovaniya-odnorazovyh-telefonov-476675

  6. AlbertDuM表示:

    buy Lisinopril online: buy Lisinopril online – buy Lisinopril online

  7. textilfolie表示:

    Thanks , I have recently been searching for information about this topic for a long time and yours is the best
    I’ve discovered so far. However, what about
    the bottom line? Are you sure about the source?

  8. mcd99表示:

    you are in reality a just right webmaster. The site loading velocity is incredible.

    It seems that you are doing any distinctive trick. Furthermore, The contents are
    masterpiece. you’ve done a great activity in this matter!

  9. Sazryuf表示:

    Покупка диплома о среднем полном образовании: как избежать мошенничества?
    kino.10bb.ru/viewtopic.php?id=164270#p277492

  10. Chad Tran表示:

    Your insights into environmental impacts are much appreciated! Check out another informative website discussing sustainable options at hot water heater replacement

  11. DarrenUnjuh表示:

    http://plavixclo.com/# п»їplavix generic

  12. Hello, Neat post. There’s a problem with your web site in web explorer, might test this?
    IE still is the market chief and a good component of people will
    miss your fantastic writing because of this problem.

  13. BernardMop表示:

    buy Lisinopril online buy Lisinopril 1st buy Lisinopril 1st

  14. BrandenSlomy表示:

    amoxicillin 30 capsules price: Com Pharm – amoxicillin 500 mg brand name

  15. It’s great that you are getting thoughts from this piece of writing as well as from our discussion made at this time.

  16. 10 Best Mobile Apps For Mazda 6 Key lost mazda keys (http://www.Stes.tyc.edu.Tw/)

  17. BernardMop表示:

    buy cytotec cytpremium order cytotec online

  18. Sazrotb表示:

    Реально ли приобрести диплом стоматолога? Основные этапы

    odesit.com/user.php?id.14271

  19. AlbertDuM表示:

    lisinopril 2.5 pill: buy Lisinopril 1st – buy Lisinopril 1st

  20. Sweet blog! I found it while surfing around on Yahoo News.

    Do you have any suggestions on how to get listed in Yahoo
    News? I’ve been trying for a while but I never seem to get
    there! Thanks

  21. 15 Gifts For The Adults Toys Lover In Your Life best adult sex Toys

  22. BrandenSlomy表示:

    rexall pharmacy amoxicillin 500mg: Amoxicillin for sale – amoxicillin 250 mg price in india

  23. Great insights on SEO advertising! It’s fascinating exactly how the landscape is regularly advancing. I’ve located that making use of social media sites alongside search engine optimization can really increase traffic search engine optimization company

  24. BrandenSlomy表示:

    cost of prednisone 40 mg: buy prednisone – prednisone 20 mg in india

  25. Bokep Viral表示:

    Hi there, I would like to subscribe for this weblog to obtain newest updates, so
    where can i do it please help.

  26. Sazrbol表示:

    Реально ли приобрести диплом стоматолога? Основные шаги
    behealthy.maxbb.ru/site/login

  27. Greetings! I’ve been following your weblog for a while now and finally got the bravery to
    go ahead and give you a shout out from Humble Texas!

    Just wanted to say keep up the good work!

發佈留言

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