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,373,225 Responses

  1. Michaelkeymn表示:

    Наша юкос «Сайт числом мебели для кухни» воспламеняется созданием да реализацией качественной кухонной мебели. Наша сестра делаем отличное предложение широкий ассортимент продукта, яже парирует наиболее современным образцам а также направленностям дизайна https://sufebey8kuhnishki.ru/.

  2. JamesBuice表示:

    mexican mail order pharmacies: mexican pharmacy – mexico pharmacies prescription drugs
    mexican pharmaceuticals online

  3. Jamesruigo表示:

    http://indiadrugs.pro/# world pharmacy india

  4. I do not even know how I ended up here, but I
    thought this post was good. I do not know who you are but certainly you are going to a famous blogger if you are not already 😉 Cheers!

    My website: foundation repair Texas

  5. Why You Should Focus On Improving Ghost Immobiliser Installation autowatch ghost Immobiliser installation

  6. I’ve been browsing online more than three hours today, yet I never found any interesting article like yours.
    It’s pretty worth enough for me. Personally, if all web owners and bloggers made good content as you did, the net
    will be much more useful than ever before.

  7. 20 Questions You Should Always ASK ABOUT Folding Wheelchair Before You Buy Folding Wheelchair Buy Folding Wheelchair

  8. MichaelNed表示:

    best online canadian pharmacy: Cheapest online pharmacy – canadian pharmacy online reviews

  9. RobertWAisa表示:

    purple pharmacy mexico price list medication from mexico mexico drug stores pharmacies

  10. I truly love your site.. Pleasant colors & theme. Did you make this web site yourself?
    Please reply back as I’m looking to create my own blog and would like to learn where you got this from or just what the theme is called.

    Cheers!

    Also visit my website HD Foundation Repair

  11. MichaelNed表示:

    legit canadian pharmacy: Cheapest online pharmacy – canadian pharmacy king reviews

  12. 120.79.79.110表示:

    See What Situs Terpercaya Tricks The Celebs Are Using Situs Terpercaya (120.79.79.110)

  13. 10 Automobile Locksmiths Near Me-Related Projects That Stretch Your Creativity autolocksmith near me

  14. Профессиональный сервисный центр по ремонту посудомоечных машин с выездом на дом в Москве.
    Мы предлагаем: диагностика и ремонт посудомоечной машины
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  15. Greetings! Very helpful advice in this particular article!
    It’s the little changes which will make the biggest changes.
    Many thanks for sharing!

  16. MichaelNed表示:

    buy medicines online in india: online Indian pharmacy – best online pharmacy india

  17. Hey very interesting blog!

    Also visit my website … foundation repair tips

  18. Jamesruigo表示:

    https://mexicanpharma.icu/# mexico pharmacies prescription drugs

  19. Jamesruigo表示:

    http://mexicanpharma.icu/# purple pharmacy mexico price list

  20. kkoKep表示:

    Монтаж и проектирование вентиляции в Екатеринбурге https://klimat-kom.com/

  21. I am so joyful that this series is over and that I won’t ever decide up any of these books from this collection again for as long as I reside.
    I am the definition of executed. Also, spoilers shall be
    abound and aplenty throughout this whole overview, and this goes to
    a a principally Supernatural gif-filled
    extravaganza, because A). That’s how angels/demons/and many others.
    should be achieved and B). I can. So if you do not like spoilers or Supernatural, depart now,
    as a result of shit’s about to get ugly up in here

  22. Feel free to surf to my page :: Daycares By Category

  23. Pretty! This was an extremely wonderful post. Many thanks for supplying this information.

    Have a look at my blog; concrete foundation repair

  24. 789win表示:

    That is a very good tip especially to those fresh to the blogosphere.

    Brief but very precise info… Appreciate your sharing this one.
    A must read post!

  25. MichaelNed表示:

    Online medicine home delivery: Indian pharmacy online – india pharmacy mail order

  26. Appreciate this post. Will try it out.

  27. RobertWAisa表示:

    canadian pharmacy price checker reputable canadian pharmacy best online canadian pharmacy

  28. Nice post. I was checking continuously this blog and I
    am inspired! Very helpful information specifically the ultimate part 🙂 I care for such
    info much. I used to be seeking this particular information for a long time.
    Thank you and good luck.

  29. My coder is trying to convince me to move to .net from PHP.
    I have always disliked the idea because of the expenses. But he’s tryiong
    none the less. I’ve been using Movable-type on various websites for about a year
    and am anxious about switching to another platform.
    I have heard good things about blogengine.net.
    Is there a way I can import all my wordpress content into it?

    Any kind of help would be greatly appreciated!

  30. Dnrtnms表示:

    Официальная покупка диплома ПТУ с упрощенной программой обучения
    kentec.kr/bbs/board.php?bo_table=qna&wr_id=114815

發佈留言

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