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

  1. Hi there! I just wanted to ask if you ever have any issues with
    hackers? My last blog (wordpress) was hacked and I ended up losing a few months of hard work
    due to no backup. Do you have any solutions to stop hackers?

  2. 3 Reasons Your Mesothelioma Is Broken (And How To Fix It)
    mesothelioma claims

  3. Exness表示:

    The author is called Roseline and she totally loves this
    name. Hiring is where her primary income originates from.

    Maryland has always been my home and Do not plan on changing the concept.

    One of the things I really like most is to keep birds
    but Irrrve never made any money with the situation.

  4. What Is The Best Place To Research Mitsubishi Key Online
    Lost Car Key Locksmith Near Me

  5. www.1job.ch表示:

    Generally I do not learn post on blogs, however I wish to say that this write-up very pressured me to take
    a look at and do so! Your writing taste has been amazed me.
    Thanks, quite great article.

  6. Сразу же после запуска игры вы погружаетесь в атмосферу праздника благодаря ярким и красочным
    символам, олицетворяющим различные сладости и фрукты.

    Графика высокого качества и веселая музыка создают идеальное праздничное настроение.
    Sweet Bonanza Xmas – это уникальный слот, разработанный компанией Pragmatic
    Play, какой предлагает уймища интересных функций: Где
    играть в Свит бонанза Xmas ? Sweet Bonanza Xmas
    – это отличный предпочтение для всех любителей азартных
    игр, которые ценят красочный дизайн, захватывающий игровой процесс
    и высокие шансы на выигрыш.
    Не упустите вероятность окунуться в атмосферу праздника и получить крупные выигрыши с Sweet Bonanza Xmas!

    Сразу же после запуска игры вы
    погружаетесь в атмосферу праздника благодаря ярким и красочным символам,
    олицетворяющим различные лакомства и фрукты.
    Графика высокого качества и веселая
    музыка создают идеальное праздничное расположение.

  7. Howdy! This blog post couldn’t be written any better! Looking at this post
    reminds me of my previous roommate! He always kept preaching about
    this. I most certainly will send this post to
    him. Fairly certain he will have a good read. Thank you for sharing!

  8. KevinSounc表示:

    http://sweetbonanza.network/# sweet bonanza demo

  9. my site表示:

    Hi there, You’ve done a great job. I will certainly digg it and personally recommend to my friends.
    I am sure they will be benefited from this web site.

  10. Meds prescribing information. What side effects?
    cost generic lansoprazole without insurance
    All news about meds. Get information now.

  11. Hi there, I want to subscribe for this website to take most up-to-date updates, thus where can i do
    it please assist.

  12. KevinSounc表示:

    http://sweetbonanza.network/# sweet bonanza 90 tl

  13. The 10 Most Terrifying Things About Bentley Mulsanne Key Bentley Mulsanne Key

  14. fxpro mt5表示:

    Luigi McKnight is historical past of the my parents gave me but I never really liked that name.
    Maryland is location she loves most. To read books is one of the a few love mainly.
    Hiring is what I for an income.

  15. Volkswagen Car Key Replacement’s History History Of Volkswagen Car Key Replacement new volkswagen key

  16. Imogene表示:

    Are You Responsible For An Fiat Key Replacement Budget?
    12 Best Ways To Spend Your Money lost fiat 500 key – Imogene

  17. Attractive section of content. I just stumbled upon your web site and in accession capital to assert
    that I acquire in fact enjoyed account your blog posts.

    Any way I’ll be subscribing to your feeds and even I achievement you access consistently quickly.

  18. Great post. I was checking continuously this weblog and I’m impressed!
    Very helpful info particularly the ultimate phase 🙂
    I handle such information a lot. I was seeking this particular information for a long time.
    Thanks and good luck.

  19. Consequentemente, a redstar foi adquirida pela ipoker, https://brazilredstarpokerpro.com/ o que trouxe para World Wide Web uma nova causa raiz tráfego e permitiu que a sala continuasse seu caminho.

  20. Darrelherse表示:

    en iyi slot siteleri: deneme bonusu veren siteler – yeni slot siteleri

  21. This post is worth everyone’s attention. Where can I find out more?

  22. 25 Surprising Facts About Upvc Sash Windows upvc windows repair near me

  23. In recent years, the burgeoning interest in cannabidiol (CBD) products has led to a diverse market crowded with various formulations and brands.

  24. What Is Mesothelioma Lawsuit? To Utilize It mesothelioma case
    (http://www.safe1.co.kr/)

  25. It’s truly a great and helpful piece of information. I am happy that
    you simply shared this helpful info with us. Please
    stay us up to date like this. Thanks for sharing.

發佈留言

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