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,237,658 Responses

  1. wps 官网表示:

    I know this if off topic but I’m looking into starting my own blog
    and was curious what all is required to get set up? I’m assuming having a
    blog like yours would cost a pretty penny? I’m not
    very internet smart so I’m not 100% certain. Any tips or advice would be
    greatly appreciated. Thanks

  2. Nine Things That Your Parent Teach You About Lamborghini Huracan Key lamborghini huracan key (kokholm-dyhr-2.Blogbright.net)

  3. CarrollUnton表示:

    deneme bonusu veren siteler yerliarama.org http://casinositeleri.win/# Canl? Casino Siteleri

  4. Diplomi_mper表示:

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

  5. LarryCoell表示:

    Casino Siteleri casino siteleri win Deneme Bonusu Veren Siteler

  6. Medicament information sheet. What side effects can this medication cause?
    can i order sinemet no prescription
    Actual information about medicament. Read information here.

  7. fakenews.win表示:

    10 Things You Learned From Kindergarden They’ll Help
    You Understand Suzuki Key Fob Replacement Suzuki key
    replacement (fakenews.win)

  8. Derekfar表示:

    en cok kazand?ran slot oyunlar?: slot tr online – slot oyunlar? puf noktalar?

  9. Derekfar表示:

    matadorbet giris: matadorbet – matadorbet bid

  10. Uazrsth表示:

    Узнайте стоимость диплома высшего и среднего образования и процесс получения
    pfr030.ru/kupit-attestat-ob-okonchanii-9-klassov-v-taraze.html

  11. ClydePab表示:

    slot oyunlar? puf noktalar?: slot siteleri – slot oyunlar? puf noktalar?

  12. ClydePab表示:

    slot oyunlar? puf noktalar?: en cok kazand?ran slot oyunlar? – en cok kazand?ran slot oyunlar?

  13. I don’t know whether it’s just me or if everyone else encountering issues with your blog.

    It appears like some of the written text on your posts are running off the screen. Can somebody else please comment and
    let me know if this is happening to them as well? This may be a problem
    with my web browser because I’ve had this happen before. Appreciate it

  14. I’ll right away snatch your rss as I can’t to find your email subscription hyperlink or e-newsletter service.

    Do you’ve any? Kindly permit me recognize so that
    I may subscribe. Thanks.

    https://ww1.hongkongpols.club/

  15. Ten Window Friction Hinges Myths You Should Not Share On Twitter window hinge replacement cost

  16. Derekfar表示:

    ultrabet tr online: ultrabet giris – ultrabet tr online

  17. Diplomi_kner表示:

    купить диплом дерматолога prema365-diploms.ru .

  18. My family every time say that I am wasting my time here at net, however I know I am getting knowledge
    all the time by reading thes good posts.

    My blog post – best advertisements

  19. Www.pdc.edu表示:

    Buying Patio Gas Tools To Make Your Daily Lifethe One Buying Patio Gas Trick That Every Person Should Know buying patio gas (http://Www.pdc.edu)

  20. AaronBlupe表示:

    Создание лендингов под ключ в студии в Москве включает проектирование, дизайн и программирование, обеспечивающее эффективность и удобство использования. Также предоставляются услуги: оптимизация для Яндекс и Google, настройка рекламных кампаний, поддержка, обслуживание и ведение маркетинга studiya poddergki

  21. Adult ADHD Diagnostic Assessment And Treatment Tools To Help You Manage Your Daily Lifethe One Adult ADHD Diagnostic Assessment And Treatment
    Trick That Should Be Used By Everyone Learn adult adhd
    diagnostic Assessment and treatment (https://Kryger-Mikkelsen-2.technetbloggers.de/ten-startups-that-will-revolutionize-the-adhd-in-adults-assessment-industry-for-the-better-1726620930)

  22. I have fun with, lead to I discovered exactly what I used to be
    looking for. You’ve ended my four day lengthy hunt! God
    Bless you man. Have a great day. Bye

  23. What’s up, yeah this article is actually pleasant and I have learned lot of
    things from it about blogging. thanks.

    my blog post … 香港訂造傢俬

  24. I absolutely love your blog and find almost all of your post’s to be
    precisely what I’m looking for. Does one offer guest writers to write content for yourself?
    I wouldn’t mind composing a post or elaborating on a few of the subjects you write related to here.
    Again, awesome site!

  25. Derekfar表示:

    matadorbet.bid: matadorbet bid – matadorbet

發佈留言

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