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,365,856 Responses

  1. Wonderful article! We will be linking to this great content on our website.
    Keep up the good writing. https://Oke.zone/profile.php?id=121498

  2. Your Family Will Be Grateful For Getting This Pragmatic 프라그마틱 무료 – https://Bookmarkleader.Com

  3. Amanda Hudson表示:

    Shoutout to moving services for the amazing help during my recent move in

  4. Ralph Cooper表示:

    ”Impressed by your take regarding creating immersive digital experiences- let’s explore immersive elements featured within mine Over Here :# # anyKeyWord # # local search engine optimization

  5. Very nice post. I just stumbled upon your blog
    and wanted to say that I have truly enjoyed surfing around your weblog
    posts. After all I’ll be subscribing on your rss feed and I’m hoping you
    write once more soon!

  6. KennethPah表示:

    where to buy generic clomid pill clomid without rx where can i get generic clomid pills

  7. 14 Misconceptions Commonly Held About Robotic Vacuum Cleaner robotic vacuum cleaner amazon

  8. I really like what you guys are up too. This sort of clever work and
    exposure! Keep up the wonderful works guys I’ve added you guyus to my blogroll. https://f2b.s3-web.eu.cloud-object-storage.appdomain.cloud/

  9. Здесь можно купить домашний сейф в интернет магазине сейф домашний купить

  10. Здесь можно где можно купить сейф для дома сейфы домашние москва

  11. 10 Facts About Pragmatic Product Authentication That Can Instantly Put You In A Good
    Mood 프라그마틱

  12. For Whom Is Hyundai Ix35 Key Replacement And Why You Should
    Take A Look 2017 Hyundai Accent Key Replacement

  13. RobertJar表示:

    where to buy prednisone without prescription: buy prednisone 10mg – prednisone prices

  14. Great information. Lucky me I recently found your
    website by chance (stumbleupon). I’ve saved as a
    favorite for later! benicetomommy.com

  15. webpage表示:

    Получайте кэшбэк до 5% на каждый покупку с картой Сбербанка!
    Экономьте на покупках в магазинах,
    кафе и онлайн. Простое оформление и удобное управление через мобильное приложение.

    Начните экономить уже сегодня!======>
    ВТБ – Карта для жизни в Ессентуках

  16. Genevieve表示:

    The Three Greatest Moments In Drip Brew History drip maker (Genevieve)

  17. 7 Practical Tips For Making The Profits Of Your Sofas And Couches new Couch for sale

  18. Marco表示:

    How To Build A Successful Car Key Replacement Near Me Even If You’re Not Business-Savvy replacement car keys cost uk (Marco)

  19. Ola Carroll表示:

    Love how you explained the various styles of retaining walls; it really helps narrow down choices! Will contact retaining wall contractor

  20. SamuelBix表示:

    amoxicillin 500mg capsules uk: amoxicillin 500 coupon – amoxicillin 500mg buy online canada

  21. Tabletop表示:

    We are a group of volunteers and starting a new scheme in our community.
    Your site provided us with valuable information to work on. You’ve done
    an impressive job and our whole community will be thankful to you.

  22. Hi, i beliеve tha i saww yyou vikѕіted myy wewblog ѕso i ցgot һeere too reʏurn thee want?.I aam tryinmg tto
    too fiknd thinngs tⲟo enhancxe mmy site!I suppos iits adequate tto uuse somme
    oof your ideas!!

    Heere iss myy sie کسب درآمد آسان از اینترنت

  23. Здесь можно купить сейфы для дома сейф для дома

  24. Здесь можно купить домашний сейф сейфы для дома цены

  25. Предлагаем услуги профессиональных инженеров офицальной мастерской.
    Еслли вы искали ремонт телефонов honor, можете посмотреть на сайте: ремонт телефонов honor цены
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  26. suka casino表示:

    You expressed this adequately!

  27. ThelmaFange表示:

    On our website you will find a unique assortment rare coins from all over the world. We offer both modern and historical specimens that will become real finds for lovers of numismatics.
    For more information, follow the link 15 копеек 1962 года цена
    Our team of experts carefully selects each coin, ensuring authenticity.

  28. KennethPah表示:

    where to buy generic clomid for sale clomidonpharm can i buy generic clomid without a prescription

發佈留言

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