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,372,337 Responses

  1. 15 Shocking Facts About Glazing Specialists London That You Didn’t Know home Window repair London

  2. В магазине сейфов предлагают сейфы сейфы купить

  3. нарколог на дом вывод из запоя ростов нарколог на дом вывод из запоя ростов .

  4. В магазине сейфов предлагают сейф москва сейфы простые

  5. WOW just what I was looking for. Came here by searching
    for kraken тор

  6. How To Choose The Right Replace Upvc Door Panel Online Replacement Upvc Door Panels (Fakenews.Win)

  7. Five Killer Quora Answers On Daftar Situs Togel Daftar Situs Togel

  8. В магазине сейфов предлагают сейф купить где купить сейф

  9. Eula Beaufort表示:

    Five Killer Quora Answers On How To Find A Womens G Spot how to find A womens g Spot

  10. Maddison表示:

    At this moment I am going away to do my breakfast,
    after having my breakfast coming over again to read more news.

  11. Michaelkeymn表示:

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

  12. xnxx.surf表示:

    It’s going to be finish of mine day, however before finish I am reading this wonderful
    article to increase my know-how.

  13. Odette Stuart表示:

    I’m curious to find out what blog system you happen to be working with? I’m having some minor security issues with my latest website and I would like to find something more safeguarded. Do you have any recommendations?

  14. Frankevild表示:

    http://ozempic.art/# buy ozempic

  15. Jeremypag表示:

    cheapest rybelsus pills semaglutide tablets semaglutide tablets

  16. Madelaine表示:

    When someone writes an article he/she retains the thought of a
    user in his/her mind that how a user can be aware of it.
    So that’s why this paragraph is amazing. Thanks!

  17. Test: How Much Do You Know About Audi A1 Key?audi keyless entry

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

  19. Lydia Wortham表示:

    What Is Audi Battery Key Replacement And Why Is Everyone Dissing It?Audi Etron Key – Followmedoitbbs.Com

  20. Gita Danis表示:

    9 . What Your Parents Teach You About Capsule Machine Coffee capsule machine coffee

  21. Highly descriptive article, I loved that a lot. Will there be a part 2?

  22. I really like reading an article that can make people think.
    Also, many thanks for permitting me to comment!

  23. Are You In Search Of Inspiration? Check Out Audi Lost Key In My Area

  24. Have you ever thought about including a little bit more than just your
    articles? I mean, what you say is important and
    all. But imagine if you added some great visuals or video clips to give your posts more, “pop”!
    Your content is excellent but with images and clips, this blog could undeniably be
    one of the greatest in its niche. Amazing blog!

  25. 10 Things That Your Family Taught You About Electric Treadmill Cheap electric treadmill cheap (Kai)

  26. BarryDof表示:

    http://rybelsus.shop/# buy rybelsus online

  27. LeroyAcuff表示:

    Профессиональный сервисный центр ремонт телефонов цены ремонт старых телефонов

發佈留言

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