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,232,680 Responses

  1. gzbqurbnc表示:

    Forex Trading SessionsWhat time the Forex Market opens in South AfricaForex Trading Tax in South AfricaBest banks for Forex Trading in South Africa Advertiser Disclosure: BrokerNotes.co helps investors across the globe by spending over 1,000 hours each year testing and researching online brokers. How do we make money? Our partners compensate us through paid advertising. While partners may pay to provide offers or be featured, e.g. exclusive offers, they cannot pay to alter our recommendations, advice, ratings, or any other content throughout the site. Furthermore, our content and research teams do not participate in any advertising planning nor are they permitted access to advertising campaign data. Here’s how we make money:. The total amount of underlying assets per derivative contract is called lot size. For example, forex lot size refers to the total amount of the base currency of a futures or options contract. Indian currency pairs usually trade in a lot size of 1000 of the base currency. Forex trading in India has the following lot sizes-
    https://directory-2020.com/listings346310/copy-trading-forex-brokers
    This review covers facts about what the broker offers and discusses its major advantages and disadvantages. After reading this review, you’ll know whether Forex is available in and whether it’s for you. We assess, rate, and rank dozens of international forex brokers. Here are a few. MT4 is the best Forex platform, which benefits from functionality and relative ease of operation. But Forex traders without experience will have to spend some time exploring the interface. Its major advantage is hundreds of free auxiliary applications that are integrated into the platform within a minute. You can learn more about this terminal in our review What is MetaTrader. Forex is the number one forex (FX) broker in the US, based on client assets per the 2019 monthly Retail Forex Obligation reports published by the CFTC.

  2. Easydrorbix表示:

    watch tour de pharmacy online free: best online pharmacy cialis – seroquel pharmacy assistance

  3. Drstobeese表示:

    polish pharmacy online usa: ventolin uk pharmacy – anti viral

  4. Pinterest表示:

    Hi there, I discovered your website via Google at the same time as
    looking for a similar subject, your web site came up, it seems to be good.
    I’ve bookmarked it in my google bookmarks.[X-N-E-W-L-I-N-S-P-I-N-X]Hello there, simply
    became alert to your weblog through Google,
    and located that it’s truly informative. I’m going to be careful
    for brussels. I will appreciate when you continue this in future.
    A lot of folks will probably be benefited out
    of your writing. Cheers!

    Check out my web-site :: Pinterest

  5. вывод из запоя дешево ростов http://www.vyvod-iz-zapoya-rostov12.ru/ .

  6. Easydrorbix表示:

    viagra at tesco pharmacy: rite aid 24 hour pharmacy store locator – online pharmacy glucophage

  7. Drstobeese表示:

    pharmacy store nearby: cytotec pharmacy online – Viagra Soft Flavored

  8. Its like you read my mind! You appear to know a lot about this, like you wrote the book in it or something.
    I think that you could do with some pics to drive the message home a bit, but
    instead of that, this is magnificent blog. A fantastic read.
    I will definitely be back.

  9. pvhoqmhlu表示:

    Some brokers advertise zero spread forex accounts. This sounds too good to be true and, unfortunately, it is. With this type of account, the spreads are not really zero, but they do tend to be small. In addition, with a zero spread account, you will be charged a commission on every trade that is opened, regardless of whether it is going to be a winner or a loser. A swap is an agreement for a financial exchange in which one of the two parties promises to make, with an established frequency, a series of payments, in exchange for receiving another set of payments from the other party. These flows normally respond to interest payments based on the nominal amount of the swap. Insta Global Ltd., зареєстрована FSC Сент-Вінсент, Шемрок Лодж, Мюррей Роад, Кінгстаун, Сент-Вінсент, реєстраційний номер 24321 IBC 2017.
    https://emiliodecb852963.ampedpages.com/forex-broker-welcome-bonus-no-deposit-in-hindi-56791765
    Other brokers offer variable spreads but with Trade Nation’s low-cost
fixed spreads, when the markets move, your costs don’t. It’s no wonder we’re the pioneers of trust, value and transparency in trading. So, no matter how experienced you are at trading, you can thrive at Trade Nation. Oanda is headquartered in the United States, but there are numerous international offices in cities such as London and Tokyo. Altogether, this online broker has 8 international financial hubs and customers from more than 196 countries. Oanda has licenses from leading regulatory jurisdictions in the United States, the United Kingdom, Australia, Singapore, Japan, and Canada.   ➡️Fundamental Analysis – The platform offers fundamental analysis guidance for traders, guiding them in collecting and evaluating market data, and understanding economic indicators and events that can influence market prices, which is crucial for those relying on the country’s economic health rather than just price fluctuations.

  10. BOMSLOT表示:

    Appreciating the hard work you put into your site and
    detailed information you offer. It’s great to come across a blog every once in a
    while that isn’t the same unwanted rehashed information. Great read!
    I’ve bookmarked your site and I’m including your
    RSS feeds to my Google account.

  11. zx.greit.si表示:

    14 Questions You Shouldn’t Be Uneasy To Ask Lost Keys Car lost car key Near me (zx.greit.si)

  12. xdpehgoca表示:

    I got access to options app of @DhanHQ . Blown away by the ease of placing trade and brokerage calculation.For someone who ends up placing more than 20 intraday orders on an avg this thing is insanely powerful and cost effective. Wow!In love with the product. @BeingPractical 🔥🔥 Pros and Cons: We invest in every brokerage account to compare deposit and withdrawal services, talk to support, place real trading orders to test the real quality and how easy or hard it is to use the website. We record account opening information of the broker that is difficult and unclear. Forex trading within Indian exchanges is getting quite popular in India, as it is creating opportunities to make money quickly. Further, SEBI regulated forex brokers in India are trusted by many to deal in currency markets and currency futures.
    https://large-directory.com/listings12819673/forex-broker-killer-online-services
    The Foreign Exchange Market (Forex) is one of the world’s largest, most liquid and most dynamic financial markets. It gives traders a platform to speculate on the value of one currency against another. Currency trading is an attractive option for investors looking to diversify their portfolios while capitalizing on global trends. Essentially, the currency market involves buying and selling currency pairs from across the world. The risks of loss from investing in CFDs can be substantial and the value of your investments may fluctuate. 70% of retail client accounts lose money when trading CFDs, with this investment provider. CFDs are complex instruments and come with a high risk of losing money rapidly due to leverage. You should consider whether you understand how this product works, and whether you can afford to take the high risk of losing your money.

  13. I blog frequently and I really appreciate your content.
    This great article has really peaked my interest. I’m going
    to bookmark your website and keep checking for new details about once per week.
    I opted in for your RSS feed as well.

  14. uzhqijoae表示:

    As part of the installation of the Forex Broker Turnkey solution, we can provide comprehensive assistance, including advice on Forex rules and regulation and how to become a licensed Forex broker. Most Indian forex traders use foreign forex brokers who accept traders residing in India. With trillions of dollars moved every day, the FOREX markets have become the world’s most liquid and continuous marketplaces. Whether trading in the spot market, futures markets, or options markets, speculators and hedgers can choose an instrument and leverage that matches their needs. The FOREX markets provide a platform for dealing with currency changes, from intricate speculative methods to everyday hedging techniques. In the rapidly evolving world of Forex trading, finding the right trading platform can make all the difference. As the market continues to grow, so does the competition among trading platforms, making it essential for traders to choose the best option for their needs. The importance of selecting a suitable platform cannot be overstated, as it can significantly impact the overall trading experience and success.
    http://sanakirja.kronman.fi/index.php?title=Low_spread_forex_brokers_in_india
    Thus, Forex brokers play a vital role both directly and indirectly in simplifying the Forex trading process for professional traders. Forex brokers come in various types and facilitate trader efforts in different ways. Therefore, it is crucial to understand which type of Forex broker is best for a specific trading practice. Best New ECN Broker in Africa 2020by Global Brands Magazine With so many benefits to ECN trading, its popularity is not surprising. When you trade with an ECN Account, you experience: ECN brokers ensure direct, conflict-free access to the real market. It is not unexpected that many traders wish to work with them. So it’s crucial to pick businesses with a track record of success. We advise you to check these platforms since they have established themselves as transparent and reliable and have low commercial expenses. Every trader will find a platform for their particular needs in our list, which includes brokers with significant leverage, intriguing educational opportunities, commission-free accounts, and unique trading features. So let’s examine these alternatives more closely.

  15. Leia Everson表示:

    Truly loads of valuable facts!

  16. web cam xxx表示:

    Here’s Sally demonstrating one thing girls can faux. There are films that reverse this scenario, much too, considering that we also see movies concentrated on a person dude being the center of attention of many women of all ages. There are simple and organic approaches to assist you to start off producing sexual intercourse last for a longer time with no the use of merchandise. We can freely say that or Fuck Meets app is the greatest app if you are intrigued in perfect teenager fuck. 1981. In America, any individual can be president. The greatest factors of condoms are that you can purchase condoms effortlessly at there regional chemist retail outlet or your neighborhood pharmacy retail outlet. Even when simple political affairs have demanded that the Bush administration deal with the American Zionist lobby or the ideal-wing Shamir government of Israel, there has been a unique undertone of distrust bordering on overt hostility. The time period “chick flick” even arrived out and wrapped about this sub-classification, which later turned controversial a tag. Sometimes, it truly is not only a man and a girl they’re demonstrating in a rom-com flick. This classic Brat Pack flick experienced Duckie pining for his BFF Andie, but who was her actual superior 50 % listed here?

  17. Www.kaycb.com表示:

    Indeed, the Convention on Human Rights states that all familial sex is legal even if equally get-togethers give full consent and know the effects of their steps. They may truly feel isolated or not know how to uncover constructive shops for complicated thoughts in these instances. If you are below the age of 18 and imagine you may well be dealing with psychological incest (or aren’t certain if what you are experiencing is sexual abuse), you are not by yourself. While lots of people today might perspective taking part in with textual content as a distant type of sexual act, asb users have eroticized the simple functionality of Usenet as an details exchange medium. Occasionally I have to use skype: the client is often appropriate. You can use this tool to discover the proper therapist for you. As long as you and your lady have an being familiar with as to what kind of carry out is welcome, it truly is correctly all ideal to grab her and strip her outfits off (bearing in head that tearing buttons off an pricey shirt is not a turn-on). Since I have amplified the sum of components, I cook everthing a little bit longer than named for, maybe even two times as prolonged.

  18. eexvgknlz表示:

    The website is operated and provides content by HF Markets Group of companies, which include: The HotForex website has a wide variety of educational materials. Those who want a good understanding of the main concepts for Forex, financial markets and CFD trading can check out the HotForex e-learning and training center. The broker is a novice friendly broker by organizing webinars regularly, focusing on current trends in the markets and teaching some technical analysis techniques. A demo account with 100,000 USD virtual funds with unlimited usage can be created at the broker. They offer 24 5 customer support via phone, email and LiveChat. ©2018-2024 BrokersView EU Limited. All Rights Reserved. My experience with dominion has been pleasant and I’ve been using them since Raja launched dominion I’ve trusted them. They’ve even refunded me on a trade that shouldn’t have stopped me out. I’ve deposited thousands with them and I withdraw weekly in bitcoin to my crypto wallet which usually takes 24 hours or less.
    http://www.genina.com/user/profile/4419367.page
    In stock trading, traders can buy odd (less than 100 shares in one lot) or mixed lots (more than 100 shares in one lot). A mixed lot order consists of standard lots and odd lots. So if you want to buy a mixed lot of 598 units, you’ll need to buy 5 standard lots of 100 shares and one odd lot of 98 shares. Using a Forex Lot Size Calculator offers numerous advantages. It not only aids in protecting your account from significant losses but also helps in maximizing the efficiency of your capital. By using the calculator, you can ensure that each trade is sized correctly according to your risk tolerance and trading strategy, which is crucial for long-term success in the Forex market. Exinity Limited (forextime) with registration number C119470 C1 GBL and registration address at 5th Floor, NEX Tower, Rue du Savoir, Cybercity, 72201 Ebene, Republic of Mauritius is regulated by the Financial Services Commission of the Republic of Mauritius with an Investment Dealer License with license number C113012295, licensed by the Financial Sector Conduct Authority (FSCA) of South Africa, with FSP No. 50320 and is a licensed Over the Counter Derivative Provider.

  19. key cutter表示:

    What’s The Job Market For Mobile Car Key Cutter Professionals?
    key cutter

  20. Kopen een echt en geregistreerd rijbewijs van onze website zonder examens te schrijven of de oefentest te doen. alles wat we nodig hebben zijn uw gegevens en deze zouden binnen de komende acht dagen in het systeem worden geregistreerd. rijbewijs kopen belgië, rijbewijs kopen belgie, rijbewijs kopen in nederland, rijbewijs b belgie, rijbewijs kopen met registratie.

  21. 188bet表示:

    Great article.

  22. Tips For Explaining Replace Lost Car Key To Your Boss I lost my car keys what do i do

  23. I know this if off topic but I’m looking into starting my own weblog 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 web smart so I’m not 100 sure. Any recommendations or advice would be greatly appreciated. Cheers

  24. Easydrorbix表示:

    united states online pharmacy viagra: cymbalta pharmacy card – Albenza

  25. Easydrorbix表示:

    pharmacy 2 home finpecia: people’s pharmacy prilosec – nexium online pharmacy no prescription

發佈留言

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