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,477,140 Responses

  1. 10 Of The Top Mobile Apps To 1kg Coffee Beans 1Kg Of Coffee Beans

  2. We stumbled over here from a different web address
    and thought I should check things out. I like what I see so now i am following you.

    Look forward to going over your web page again.

    My webpage – where is provadent manufactured

  3. Truly a good deal of fantastic info.

    Also visit my site – https://mostbet-bk.cz

  4. fakenews.win表示:

    20 Tools That Will Make You More Efficient With Best
    Folding Treadmill Small Space best folding treadmill for small
    space (fakenews.win)

  5. dewa slot表示:

    Hello, all is going sound here and ofcourse every one
    is sharing information, that’s in fact excellent, keep
    up writing.

  6. Jamesses表示:

    Познакомьтесь вместе с нашим профессиональным коллективом, яже создаёт уникальную мебель, воплощая ваши грезы в течение реальность http://www.cehitae2kuhnishki.ru/.

  7. 12 Facts About Asbestos Attorney To Make You Seek Out Other People asbestos attorneys; Brockca.Com,

  8. Профессиональный сервисный центр где ремонтируют телефоны сервис смартфонов

  9. real Dollsex表示:

    A Glimpse Inside Realistic Love Dolls’s Secrets Of Realistic Love Dolls real Dollsex

  10. Thanks a lot, I like it.

    Feel free to visit my site :: https://mostbet-bk.de

  11. BrandonJer表示:

    india online pharmacy reputable indian online pharmacy п»їlegitimate online pharmacies india

  12. Looking Into The Future How Will The Used Mobility Scooters For Sale Near Me Industry Look Like In 10 Years?new mobility scooters for sale near Me

  13. Why You Should Not Think About Making Improvements To Your Tilt And Turn Window Not Closing Tilt And Turn Window Not Closing Properly

  14. Thalia Stump表示:

    10 Easy Steps To Start Your Own Pragmatic Business 프라그마틱 무료스핀

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

  16. 10 Things We All Love About Sectional Couch With Recliner modern sectional couch (Sherrie)

  17. Leonie Downey表示:

    What’s The Job Market For Best 2 In 1 Pushchair Professionals?best 2 In 1 pushchair

  18. Hello there, You’ve done an incredible job.

    I’ll definitely digg it and personally suggest to my friends.
    I am sure they’ll be benefited from this web site.

  19. joycasino表示:

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

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

  21. 10 Startups That Are Set To Revolutionize The Sports Toto 4d Latest Result Industry For The Better 토토사이트 모음; https://Sociallweb.Com/,

  22. BrandonJer表示:

    india online pharmacy mail order pharmacy india best online pharmacy india

  23. Diplomi_tsEn表示:

    купить диплом о высшем образовании в уфе купить диплом о высшем образовании в уфе .

  24. BrandonJer表示:

    best online pharmacies in mexico medicine in mexico pharmacies purple pharmacy mexico price list

  25. Annetta Inman表示:

    This Is A Guide To Auto Locksmiths Near Me In 2023 auto key fob Locksmith near Me

  26. Milford Rhea表示:

    See What Private Adult ADHD Assessment UK Tricks The Celebs Are Utilizing Private Adult Adhd Assessment Uk (Sociallytraffic.Com)

  27. Yetta Trower表示:

    The Unknown Benefits Of Black Electric Wheelchair power chairs for Handicapped

  28. Quality content is the important to interest the people to visit
    the web site, that’s what this web page is providing.

發佈留言

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