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,001 Responses

  1. нарколог на дом вывод из запоя на дому нарколог на дом вывод из запоя на дому .

  2. Michaelkeymn表示:

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

  3. What’s The Current Job Market For Autofold Mobility Scooter Professionals?

    Autofold Mobility scooter

  4. Why All The Fuss? Situs Toto? Togel hongkong

  5. pepek表示:

    Greetings! This is my first visit to your blog!
    We are a group of volunteers and starting a new project in a community in the same niche.

    Your blog provided us beneficial information to work on. You have done a extraordinary job!

  6. 5 Laws Everybody In Upvc Door Replacement Panels Should
    Know Upvc Panels For Doors

  7. A Help Guide To Toto Sites From Beginning To End 토지노 커뮤니티

  8. Hello everybody, here every person is sharing these familiarity,
    therefore it’s fastidious to read this website, and I used to pay a visit this
    web site every day.

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

  10. not safe表示:

    lesbian porn

  11. 15 Up-And-Coming Tilt And Turn Window Mechanism Bloggers You Need To Be Keeping An Eye On Tilt And Turn Window Mechanism Broken – Longisland.Com,

  12. Jeremypag表示:

    rybelsus coupon semaglutide cost rybelsus cost

  13. RamonRek表示:

    rybelsus coupon: semaglutide cost – rybelsus coupon

  14. вывод из запоя дешево ростов https://vyvod-iz-zapoya-rostov17.ru .

  15. Why people still make use of to read news papers when in this technological globe the whole
    thing is available on net?

  16. Your Family Will Be Grateful For Getting This ADHD Adults Test testing For adhd in Adults

  17. Travel Agent表示:

    Nice blog here! Also your website loads up very fast!
    What host are you using? Can I get your affiliate link to your host?
    I wish my web site loaded up as fast as yours lol

  18. This is my first time pay a quick visit at here and i am really
    happy to read everthing at alone place.

  19. What’s The Job Market For Lexus Replacement Key Cost Professionals?Lexus Replacement Key Cost

  20. Frankevild表示:

    http://rybelsus.shop/# cheapest rybelsus pills

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

  22. BrianAmese表示:

    Выше- интернет-магазин “Мебель-шмммммммебель” приглашает широкий сортамент мебели чтобы кухонь. У нас вы выберете шиздец необходимое чтобы существа уютного также функционального внутреннего убранства https://www.tyfapao6kuhnishki.ru/.

  23. For latest news you have to pay a visit web and on world-wide-web I found this website as a most excellent site for newest updates.

  24. Ambrose Viles表示:

    You’ll Never Be Able To Figure Out This Realistic Sex Dolls For Sale’s Benefits realistic sex dolls for sale

  25. hello!,I really like your writing so a lot! share we communicate more about your article on AOL?
    I need an expert on this house to solve my problem.
    May be that is you! Having a look ahead to peer you.

  26. BarryDof表示:

    https://rybelsus.shop/# semaglutide online

  27. not safe表示:

    incest porn

發佈留言

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