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,523,264 Responses

  1. Davidnof表示:

    darknet market links https://github.com/darkwebwebsites/darkwebwebsites – dark web market deep dark web

  2. MichaelGeony表示:

    legal online pharmacy coupon code https://megaindiapharm.com/# Mega India Pharm

  3. Charleskepsy表示:

    overseas pharmacy no prescription https://xxlmexicanpharm.com/# reputable mexican pharmacies online

  4. Davidmoits表示:

    Best online pharmacy: family pharmacy – Cheapest online pharmacy

  5. Ayez besoin dun produit ce, t disn dans le site? Appelez les USA, Pharmacie. Viagra en ligne, viagra libre sans prescription, 24vesti Magasin en. Generique pharmacie vente pilule viagra suisse.Prix en pharmacie vente libre. Vente de cialis, cialis 100mg canada, Akadstud Magasin en ligne. Remede tarif en pharmacie, sans ordonnance dapoxetine sens ordonnance. Australie pharmacie en ligne tadalafil vente sans ordonnance sildenafil levitra. Commander viagra en ligne, escompte viagra en ligne, Okcolab. https://eurogeneriqueetfrance.com/ibutop/ Bon Marche Ibutop Vente

  6. PENIPU表示:

    Hi Dear, are you genuinely visiting this web page daily, if so then you will
    without doubt get pleasant knowledge.

  7. I am sure this article has touched all the internet viewers, its really really pleasant paragraph on building up new weblog.

  8. Michaelkig表示:

    how to get on dark web https://github.com/darknetmarkets2025/darknetmarketlinks – the dark internet deep web drug store

  9. Hey! Do you know if they make any plugins to protect against hackers?

    I’m kinda paranoid about losing everything I’ve worked hard on. Any suggestions?

  10. Davidnof表示:

    darknet markets 2025 https://github.com/darkwebwebsites/darkwebwebsites – tor market links blackweb

  11. Petervop表示:

    Understanding the Aave Protocol
    The Aave Protocol is revolutionizing the decentralized finance (DeFi) space with its unique approach to crypto lending and borrowing. Whether you’re a seasoned investor or new to the world of cryptocurrencies, Aave offers a robust platform for managing your digital assets.
    aave protocol
    What is Aave?
    Aave, which means ‘ghost’ in Finnish, is a non-custodial liquidity protocol. It allows users to earn interest on deposits and borrow assets. Aave is known for its wide range of supported cryptocurrencies and features that enhance the security and flexibility of crypto transactions.

    Key Features of Aave Protocol
    Flash Loans: Aave introduced the concept of flash loans, which are borrowed and repaid within a single transaction. This feature is useful for arbitrage opportunities and collateral swaps.
    Security: Aave is audited by leading blockchain security firms, ensuring the safety of user funds.
    Rate Switching: Users can switch between stable and variable interest rates, offering flexibility based on market conditions.
    Wide Asset Support: Aave supports multiple cryptocurrencies including Ethereum (ETH), DAI, and more.
    How to Get Started with Aave
    Getting started with Aave is straightforward:

    Set Up a Wallet: Use a compatible crypto wallet like MetaMask.
    Connect to Aave: Visit the Aave website and connect your wallet.
    Deposit Crypto: Choose from supported cryptocurrencies to deposit into the Aave Protocol.
    Start Earning or Borrowing: Once your crypto is deposited, you can start earning interest or borrowing assets instantly.
    Advantages of Using Aave
    There are several reasons why Aave stands out in the world of DeFi:

    Non-Custodial: Users maintain control over their funds.
    Highly Secure: Regular audits and community governance enhance security.
    Innovative Products: Pioneering features like flash loans provide unparalleled opportunities.
    In conclusion, the Aave Protocol offers a revolutionary platform for anyone looking to explore the potential of decentralized finance. Whether you’re earning interest or borrowing assets, Aave provides a secure and flexible experience.

  12. Delphi Cash表示:

    This website definitely has all of the information I needed about this subject and didn’t know who to ask.

  13. Charleskepsy表示:

    canadian pharmacies not requiring prescription https://discountdrugmart.pro/# drugmart

  14. How Online Casinos Are Becoming a Worldwide Trend

    Internet-based gambling hubs have changed the betting scene, providing an unmatched level of accessibility and diversity that brick-and-mortar gambling houses struggle to rival. Recently, millions of players globally have adopted the excitement of internet-based gaming due to its accessibility, appealing qualities, and continuously increasing game libraries.

    One of the most compelling reasons of internet-based platforms is the unparalleled array of titles available. Whether you like spinning old-school slot machines, exploring narrative-rich video slots, or mastering skills in traditional table offerings like Baccarat, virtual venues feature infinite opportunities. Numerous services furthermore present live gaming streams, giving you the chance you to engage with live hosts and other players, all while taking in the authentic vibes of a traditional gambling venue in your own space.

    If you’re unfamiliar with the world of digital casinos or are looking to discover reputable operators, why not join our growing online hub? It’s a hub where enthusiasts exchange insights, helping you to enjoy more of your casino activities. Check out the connections and check it out now: aviator bet app

    In addition to diversity, virtual gaming providers shine constant connectivity.

  15. mostbet_qhpa表示:

    мостбет зеркало http://www.gtrtt.com.kg/ .

  16. MarkWat表示:

    Всем привет! Подскажите, где почитатьполезные статьи о займах? Сейчас читаю – atmosfera-fin.ru

  17. Upvc Door Panel Replacement: The Ugly Reality About Upvc Door Panel Replacement
    upvc door And side Panel

  18. Oh my goodness! Amazing article dude! Thank you, However I am encountering issues
    with your RSS. I don’t know why I cannot join it. Is there anybody
    else having the same RSS problems? Anybody who knows the answer can you kindly respond?
    Thanks!!

  19. PENIPU表示:

    I know this web page gives quality depending articles or reviews and other information, is there any
    other web page which provides such stuff in quality?

  20. Charleskepsy表示:

    foreign pharmacy no prescription https://discountdrugmart.pro/# cheapest prescription pharmacy

  21. Leon Perry表示:

    I recently finished a CPR course and it was a game changer! Highly recommend everybody to get certified. Take a look at more at Emergency First Aid Training

  22. Davidmoits表示:

    family pharmacy: online pharmacy delivery usa – Best online pharmacy

  23. WillieRap表示:

    best canadian pharmacy to order from: easy canadian pharm – easy canadian pharm

  24. 1 vin_fdSi表示:

    вывод средств 1win http://www.bbcc.com.kg/ .

發佈留言

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