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,447,908 Responses

  1. вывод из запоя круглосуточно нижний новгород вывод из запоя круглосуточно нижний новгород .

  2. наркология вывод из запоя в стационаре наркология вывод из запоя в стационаре .

  3. Brandonnot表示:

    thecanadianpharmacy: canada drug pharmacy – cross border pharmacy canada

  4. Bit Alrex 80表示:

    Good blog you have here.. It’s hard to find good quality writing like yours nowadays.
    I really appreciate individuals like you! Take care!!

  5. Guide To 2 Seater Fabric Couch: The Intermediate Guide Towards 2 Seater Fabric Couch 2 seater fabric Couch

  6. The Secret Secrets Of Cut Car Key Spare Car Key Cutting

  7. Carrolleruck表示:

    https://canadianmdpharm.com/# canadian pharmacies
    buy canadian drugs

  8. The Reasons Bilingual Birth Injury Lawyers Isn’t As Easy As You Imagine
    Injurys Attorney Near Me

  9. CheyeJask表示:

    На сайте представлено актуальное зеркало mostbet casino, которое работает сегодня и обеспечивает доступ к полноценной игровой платформе для всех пользователей.

  10. WOW just what I was looking for. Came here by searching for
    check out here

  11. 9 Things Your Parents Teach You About Robotic Hoovers Robotic hoovers

  12. toket表示:

    You actually make it seem so easy with your presentation but I find
    this matter to be actually something which I think I would never understand.
    It seems too complicated and extremely broad for me.
    I’m looking forward for your next post, I will try to get the hang of it!

  13. Antoniofep表示:

    Bet Zula, canl? bahis konusunda benzersiz secenekler sunar. buyuk futbol kars?lasmalar? icin betzula guncel giris baglant?s? ile canl? bahis oynamaya baslayabilirsiniz.

    Betzula’n?n guvenilir altyap?s?, her cihazdan erisim imkan? tan?r. guncel duyurular? kac?rmadan yeni kampanyalardan haberdar olabilirsiniz.

    Fenerbahce ve Galatasaray gibi buyuk tak?mlar?n bahislerinizi an?nda yapabilirsiniz.

    Ayr?ca, bet zula giris linki, kullan?c?lara s?n?rs?z erisim sunar. Ozel olarak, bet zula giris, kolay ve h?zl? giris imkan?.

    Betzula, mobil uyumlu ve h?zl? erisim f?rsatlar?na kadar en iyi deneyimi yasatmay? amaclar. en guncel oranlar? gormek icin Betzula ile kazanmaya baslay?n!
    707707+

  14. Rickyalies表示:

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

  15. I love this site – its so usefull and helpfull.
    https://gostyn24.pl

  16. Brandonnot表示:

    canada drug pharmacy: Canadian Md Pharm – canadian pharmacy mall

  17. zeneara表示:

    Admiring the persistence you put into your site and in depth information you provide.
    It’s awesome to come across a blog every once in a while that isn’t the same outdated
    rehashed material. Great read! I’ve saved your site and
    I’m including your RSS feeds to my Google account.

  18. Guide To Free Standing Electric Fireplace With Mantel: The Intermediate Guide
    On Free Standing Electric Fireplace With Mantel electric Fireplace With mantel

  19. indian porn表示:

    I loved as much as you will receive carried out right here.
    The sketch is attractive, your authored material stylish.
    nonetheless, you command get bought an impatience
    over that you wish be delivering the following. unwell unquestionably
    come further formerly again since exactly the same nearly
    very often inside case you shield this hike.

  20. CurtisBam表示:

    Best online Indian pharmacy: Indian Cert Pharm – Best online Indian pharmacy

  21. Antoniofep表示:

    Bet Zula, canl? bahis konusunda yenilikci cozumler sunar. en heyecanl? maclar icin en h?zl? sekilde favori tak?mlar?n?za destek olabilirsiniz.

    Betzula’n?n guvenilir altyap?s?, profesyonel hizmet garantisi verir. Bet Zula sosyal medya hesaplar?yla yeni kampanyalardan haberdar olabilirsiniz.

    en onemli spor etkinliklerinin heyecan?n? Betzula ile yasayabilirsiniz.

    Ayr?ca, Betzula guncel giris adresi, mobil cihazlar uzerinden kolay erisim sunar. Ozel olarak, betzula giris, kolay ve h?zl? giris imkan?.

    Betzula, en genis bahis seceneklerinden ozel turnuvalara kadar tum kullan?c?lar?n ihtiyaclar?n? kars?lar. favori tak?m?n?z?n galibiyetini kutlamak icin simdi giris yap?n!
    707707+

發佈留言

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