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,234,483 Responses

  1. Derekfar表示:

    matadorbet.bid: matadorbet – matadorbet bid

  2. ArnPaish表示:

    Compare sales and discounts to stromectol price uk return shipment if the product is ineffective?

  3. item670338815表示:

    My spouse and I stumbled over here from a different web page and thought I might check things
    out. I like what I see so now i am following you. Look forward
    to finding out about your web page again.

  4. 10 Best Facebook Pages That I’ve Ever Seen.
    Private ADHD Diagnosis Near Me Private adhd assessment isle of wight (Redhotbookmarks.com)

  5. 5 Killer Quora Answers To Audi A4 Key Replacement
    Audi A4 Key Replacement

  6. ClydePab表示:

    guvenilir casino siteleri: guvenilir casino siteleri – Deneme Bonusu Veren Siteler

  7. LarryCoell表示:

    Canl? Casino Siteleri guvenilir casino siteleri Casino Siteleri

  8. HassanbuifS表示:

    http://slot-tr.online/# slot oyunlar?
    deneme bonusu veren siteler

  9. Derekfar表示:

    guvenilir casino siteleri: Deneme Bonusu Veren Siteler – Canl? Casino Siteleri

  10. HassanbuifS表示:

    https://ultrabet-tr.online/# ultrabet yeni giris 1125
    deneme bonusu veren siteler betturkey betturkey.com

  11. Even we find ourselves making video content on Instagram quite often.

  12. LarryCoell表示:

    deneme bonusu veren siteler denemebonusu2026.com deneme bonusu veren siteler mycbet.com deneme bonusu veren siteler 2024

  13. CarrollUnton表示:

    deneme bonusu veren siteler denemebonusu2026.com https://casinositeleri.win/# Casino Siteleri

  14. I all the time used to read piece of writing in news papers but now as I am
    a user of internet therefore from now I am using net for articles or reviews,
    thanks to web.

  15. LarryCoell表示:

    matadorbet.bid matadorbet matadorbet bid

  16. Hi there! Quick question that’s completely off topic.
    Do you know how to make your site mobile friendly?
    My website looks weird when viewing from my iphone
    4. I’m trying to find a theme or plugin that might be able to correct this problem.

    If you have any suggestions, please share. Thanks!

  17. This info is priceless. How can I find out more?

  18. Diplomi_qakn表示:

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

  19. situs gacor表示:

    Hi there, I enjoy reading through your article post.
    I like to write a little comment to support you.

  20. CarrollUnton表示:

    deneme bonusu veren siteler betturkey http://ultrabet-tr.online/# ultrabet bonus

  21. Guide To Car Key Repairs Near Me: The Intermediate Guide In Car Key Repairs
    Near Me Car Key Repairs

  22. Attractive part of content. I just stumbled upon your web site and in accession capital to say that I get in fact loved account your blog posts.
    Any way I’ll be subscribing on your feeds or even I success you get admission to persistently fast.

  23. Diplomi_dpMl表示:

    купить диплом образования в иркутске many-diplom77.ru .

  24. Ethereum (ETH)
    In the fast-paced realm of digital currencies, new possibilities emerge daily.
    One particular platform has captured the imagination of tech enthusiasts and investors
    alike. Its unique capabilities allow developers to
    create a variety of applications. This not only transforms the
    way we think about transactions but also revolutionizes traditional
    systems.
    Imagine a place where innovation and finance intertwine seamlessly.
    Where smart contracts work as agreements without intermediaries.

    This decentralized environment brings trust and security as foundational principles.
    The architecture is designed to be open and accessible, inviting participation from all corners of the globe.

    As users dive deeper into this innovative ecosystem, they encounter
    a vibrant community. The platform thrives on collaboration and creativity, which fuels continuous development.

    Enhanced by a wide array of tools, individuals and
    businesses can unlock their potential like never before.

    It’s fascinating how one can create, trade, and interact in ways that were once considered out of
    reach.
    With every passing day, the excitement around this groundbreaking technology increases.
    Individuals are exploring its implications not just for currency,
    but for various sectors, from finance to art. It’s
    truly a paradigm shift–a fusion of code, finance, and community that shapes our digital future.

    The Role of Smart Contracts in the Blockchain Space
    At the core of decentralized platforms lies
    a fascinating concept that has revolutionized the way agreements
    are executed. Imagine a world where trust is built into the
    code itself, eliminating the need for intermediaries. Smart contracts are essentially
    self-executing contracts with the terms of the agreement directly written into lines
    of code. These digital agreements operate automatically when predefined conditions are met,
    offering a level of efficiency and reliability that traditional contracts often lack.

    In essence, they serve to facilitate, verify, or enforce the negotiation or performance of a contract.
    This process minimizes the risk of human error and fraud.
    For instance, think about an escrow service in real
    estate. Typically, this transaction requires multiple parties and can often drag on due to delays.
    However, with smart contracts, once the buyer’s funds are verified, ownership can be automatically
    transferred without the need for additional steps.

    It’s a simple, yet powerful idea. Smart contracts utilize blockchain technology,
    ensuring that all transactions are recorded in a transparent and immutable manner.
    This means once a contract is deployed on the
    network, it cannot be altered or tampered with. This significantly enhances the
    security aspect. Participants can confidently interact with one
    another without worrying about potential deceit.

    Moreover, these innovative agreements are not confined to just financial transactions.

    They extend to various sectors, including supply chain management, healthcare, and entertainment.
    Envision a supply chain where products are tracked in real-time,
    and payments are released automatically upon delivery verification. This leads to efficiency gains.

    Cutting out intermediaries reduces costs significantly.

    In this dynamic digital landscape, the adaptability of smart contracts continues to inspire new applications and use
    cases. They offer not just speed but also reduced transaction costs, transforming how we view
    agreements entirely. As more people recognize their potential, the landscape is inevitably shifting towards more automated and trustworthy transactions.
    Therefore, this tech is reshaping industries and challenging
    traditional paradigms.
    In conclusion, smart contracts encapsulate a paradigm
    shift in how agreements are created and executed, demonstrating the power of technology
    to streamline processes and create a trustworthy environment for all participants involved.

    The Role of Smart Contracts in the Blockchain Arena
    Smart contracts have revolutionized the way transactions are executed on blockchains.
    They are self-executing agreements with the terms of the contract written directly into code.
    Imagine a scenario where trust is established not through intermediaries but through algorithms.
    This innovation has transformed numerous industries, enabling automated processes
    that save time and reduce costs. However, the implications of this technology weave a complex narrative that touches on both
    opportunity and risk.
    At their core, these automated contracts eliminate the need for third parties.
    This can lead to increased efficiency and transparency
    in various transactions. Instead of relying on a bank or legal authority, parties interact directly.
    This not only streamlines the process but also
    minimizes errors. Yet, the question remains: how do these contracts truly function?
    Essentially, when predetermined conditions are met, the contract
    executes automatically. For instance, in a real estate transaction, once the buyer funds the agreed-upon amount, ownership transfers
    seamlessly. It removes the ambiguity often associated with traditional agreements.
    However, it’s crucial to remember that while the code is
    law, it is also limited by its programming language and the foresight of its
    creators. This brings us to the importance of rigorous testing and auditing in deployment.

    Moreover, their role extends beyond simple transactions; they create
    ecosystems of decentralized applications. These apps can facilitate everything
    from lending platforms to asset trading. The brilliance lies in their ability to
    foster trust without human intervention. The trust is built into the code
    itself. As such, this technology can democratize access to complex financial instruments.

    Despite the benefits, challenges lurk in the shadows. Security vulnerabilities can lead to devastating losses.

    The infamous hacks of various platforms have raised eyebrows
    and concerns. Users must take extra precautions, understanding the risks involved.
    Hence, a strong emphasis on user education is essential in this domain.
    In summary, automated agreements are not just technological novelties; they represent a shift toward
    greater autonomy and efficiency in digital transactions.

    They challenge traditional norms and inspire
    new ways of thinking about agreements. Moreover, as more industries explore this technology,
    its potential continues to expand. With the right balance of innovation and
    precaution, we may be only scratching the surface of what this technology
    can achieve.
    The Role of Smart Contracts in Ethereum
    Smart contracts are revolutionary tools in the world of blockchain technology.
    They automate processes and eliminate the need for intermediaries.
    Picture a contract that executes itself when certain conditions are met.
    That’s the essence of this innovation. They enhance
    transparency and efficiency in transactions.
    Traditionally, contracts require lawyers and extensive
    paperwork. This often leads to delays and misunderstandings.
    With self-executing agreements, the rules are coded
    into the blockchain, making them tamper-proof.
    This level of security is unprecedented. Once initiated, the
    terms cannot be altered.
    Moreover, smart contracts facilitate trust among parties.
    In many scenarios, trust issues can lead to disputes.
    However, with automation, parties can rely on the code’s execution, rather
    than on each other’s word. This reduces the chances of fraud significantly.

    Imagine a real estate transaction. When the buyer transfers funds,
    the ownership of the property is automatically recorded on the blockchain. There’s no need to
    wait for a third party to verify the transaction. This speeds
    up the entire process immensely while ensuring transparency.

    Furthermore, industries from finance to supply chain management are embracing this technology.
    Businesses are discovering how smart contracts can cut costs and enhance
    productivity. They are rethinking how they operate, thanks to this powerful tool.

    In summary, these digital contracts are more
    than mere code snippets. They represent a profound shift in how agreements are made and enforced.
    By utilizing blockchain technology, they pave the way for a future marked by efficiency,
    security, and trust. This innovation is just the beginning of what’s
    possible.

    Here is my homepage … “https://t.me/s/cryptonetlake”

  25. ClydePab表示:

    guvenilir casino siteleri: Casino Siteleri – Casino Siteleri

  26. ClydePab表示:

    deneme bonusu veren siteler betturkey betturkey.com: deneme bonusu veren siteler betturkey – deneme bonusu veren siteler mycbet.com

  27. Way cool! Some extremely valid points! I appreciate you penning this write-up and the rest of the website is also very good.

發佈留言

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