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,521,985 Responses

  1. The Top Reasons For Buggy 2 In 1’s Biggest “Myths” About Buggy 2 In 1 May Actually Be Right
    2In1 pushchair

  2. в нем указана общая гарантия, частота попадания в
    зону призов, взносы, история МТТ, https://movie2box.com/ где стройматериал
    принимал участие.

  3. KevinSounc表示:

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

  4. What Is Mesothelioma And How To Utilize What Is Mesothelioma And
    How To Use mesothelioma lawsuit

  5. sex animal表示:

    Hi there to all, how is the whole thing, I think every
    one is getting more from this web page, and your views
    are nice designed for new visitors.

  6. Saab Key表示:

    The Most Common Saab 9-3 Replacement Key Mistake Every Beginning Saab 9-3 Replacement
    Key User Makes Saab Key

  7. Stan表示:

    Add In Adult Women: What No One Is Discussing adhd women uk (Stan)

  8. I like this blog very much, Its a really nice spot to read and
    incur information.

  9. Darrelherse表示:

    guvenilir slot siteleri: en iyi slot siteleri 2024 – 2024 en iyi slot siteleri

  10. 10 Things We Are Hating About Mesothelioma Lawsuit Mesothelioma Law Firm

  11. I really like it whenever people come together and share thoughts.
    Great blog, stick with it!

    my homepage … baking soda for sale

  12. Regards! Numerous data!

  13. 20 Fun Facts About Smeg Fridge best fridge uk

  14. How Where To Get Honda Key Cut Rose To The #1 Trend On Social Media Honda jazz
    car Key replacement; camosglobal.com,

  15. First of all I would like to say wonderful blog!
    I had a quick question that I’d like to ask if you do not
    mind. I was curious to find out how you center yourself and clear your head prior to writing.

    I have had difficulty clearing my mind in getting my ideas out there.
    I do enjoy writing however it just seems like the first 10 to 15 minutes are usually wasted just trying to figure out how to begin. Any ideas or hints?

    Thanks!

  16. Indisputable Proof You Need Private Psychiatrist Colchester
    Private Psychiatrist Hitchin; Classicalmusicmp3Freedownload.Com,

  17. We’re a group of volunteers and starting a new scheme in our community.
    Your web site provided us with valuable info to work on. You’ve done an impressive job and our whole community will be grateful to you.

  18. В нижней части страницы имеется информация о зарегистрированных клиентах
    казино, которые выиграли крупные суммы.
    Найти адрес актуального зеркала онлайн казино можно на специализированных форумах или спросить его у службы поддержки пользователей.
    Если игрок хочет получить приветственный бонус казино,
    то должен показать промокод
    на этом этапе регистрации, вписав его в специальном окне.
    Затем пользователь ставит галочку в окне, подтверждая свое совершеннолетие и соглашаясь с условиями и положениями ресурса.

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

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

  19. 5 L Sectional Sofa Lessons From The Professionals luxury sectional Sofa

  20. Real estate表示:

    It’s a shame you don’t have a donate button! I’d
    certainly donate to this outstanding blog! I suppose for now i’ll settle
    for bookmarking and adding your RSS feed to my Google account.
    I look forward to brand new updates and will talk about this website with my Facebook group.

    Talk soon!

  21. The 10 Most Scariest Things About Kia Duplicate Key kia optima car Key replacement

  22. Audi q7 key表示:

    10 Facts About Audi Keys Replacement That Insists On Putting You In A Good
    Mood Audi q7 key

  23. 🎰 более двухсот бесплатных слотов.
    «slotpark dollars» {можно использовать} {только} в
    этих играх.

    My website … Пин ап казино

  24. A Glimpse Into The Secrets Of Best American-Style Fridge Freezer American Fridgefreezer

  25. KevinSounc表示:

    https://sweetbonanza.network/# sweet bonanza nas?l oynan?r

  26. Speak “Yes” To These 5 Mental Assessments Tips mental Health assesment

發佈留言

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