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

  1. Drstobeese表示:

    peoples pharmacy: legal online pharmacy reviews – secure medical online pharmacy

  2. 10 Best Books On Treatment For ADHD Adults treatments for adhd
    (https://tulun.ir/User/emelia5655/)

  3. Blingle Jacksonville, FL
    10221-3 Beach Boulevard,
    Jacksonville, FL 32246, United Ꮪtates
    9049778928
    Yard Illumination Inspiration

  4. Easydrorbix表示:

    online pharmacy delhi: 1st rx pharmacy – flomax online pharmacy

  5. nitka.by表示:

    Fridge Freezer Bosch Techniques To Simplify
    Your Daily Lifethe One Fridge Freezer Bosch Trick That Should Be Used By Everyone Be Able To Fridge freezer (nitka.by)

  6. Easydrorbix表示:

    pantoprazole pharmacy: envision rx specialty pharmacy – trazodone pharmacy

  7. RobertPaupe表示:

    купить бомбу Существуют различные виды наркотиков, такие как опиат(героин), стимуляторы (кокаин, амфетамин), галлюциногены (ЛСД, грибочки),
    депрессанты (барбитураты), и каннабиоиды (марихуана). — это вещества, которые воздействуют на центральную нервную систему, изменяя восприятие, настроение, сознание и поведение человека. Они могут быть как легальными (например, некоторые лекарства, которые отпускаются по рецепту), так и нелегальными. Употребление наркотиков может привести к зависимости,
    негативным последствиям для здоровья и проблемам в социальной жизни.

  8. Treasure Your Input!

    I’m Glad you Found the Post Constructive.

    If you’re Eager to explore Investigating more Prospects in the online Wagering Space,
    I’d Recommend Experiencing CMD368.

    They Extend a Wide range of Enthralling Gaming
    Possibilities, Broadcasted events, and a Easy-to-navigate System.

    What I Really Value about CMD368 is their Priority to Sensible Betting.
    They have Stringent Safeguards and Options to Assist Gamblers Keep control.

    Irrespective you’re a Seasoned Player or Unfamiliar with the Bookmaking, I Suspect you’d Truly Relish
    the Journey.

    Feel free to Sign up Through the Channel and Ask if you
    have More Doubts.

    Here is my homepage – cmd368 singapore (klintkoefoed7.jigsy.com)

  9. 7234043表示:

    11 Creative Methods To Write About Coffee Maker 7234043

  10. Easydrorbix表示:

    Bupron SR: rx solution pharmacy – people’s pharmacy synthroid

  11. vrswhuyjp表示:

    A bachelor’s degree is required for most entry-level forex trader positions. A degree in economics, business administration, mathematics, statistics, finance, or a finance-related major will be beneficial, but forex traders can come from a variety of different backgrounds. An internship in a trading environment is useful, and any international experience or fluency in multiple languages can be a valuable differentiator from other applicants. As previously mentioned, it is crucial for traders to know the basics of Forex trading. Since the Forex market is known for its magnitude, it is impossible to cover all the terms related to it in one article. Nevertheless, the following terms are some of the most important forex-related definitions that you should familiarise yourself with when trading online:
    https://www.curioos.com/beforetradingab
    Hedging Function: The third function of a foreign exchange market is to hedge the foreign exchange risks. The parties in the foreign exchange are often afraid of the fluctuations in the exchange rates, which means the price of one currency in terms of another currency. This might result in a gain or loss to the party concerned. The first step in trading the forex market is to contact a broker with a global reach, as the market operates in cities such as New York, London, Tokyo, and Singapore. View our Lists Showcase 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 🔥🔥

  12. Drstobeese表示:

    rx pharmacy viagra: tadalafil india pharmacy – online pharmacies

  13. We are a group of volunteers and opening a new scheme in our community.
    Your web site provided us with valuable information to work on. You’ve done an impressive job and our entire
    community will be grateful to you.

  14. The 10 Most Scariest Things About Upvc Windows Near Me Upvc windows near me

  15. 14 Questions You’re Afraid To Ask About Titration What Is Titration In Adhd

  16. Easydrorbix表示:

    cialis pharmacy rx one: costa rica pharmacy percocet – cymbalta pharmacy prices

  17. Hey just wanted to give you a quick heads up.
    The text in your post seem to be running off the screen in Chrome.
    I’m not sure if this is a format issue or something to do with internet browser compatibility but I figured I’d post to let you know.
    The design and style look great though! Hope you get the issue solved soon. Many thanks

  18. Drstobeese表示:

    online pharmacy australia viagra: online pharmacy viagra south africa – weight loss

  19. Easydrorbix表示:

    online pharmacy stock order viagra: olanzapine online pharmacy – Prometrium

  20. Easydrorbix表示:

    avandia specialty pharmacy: rx pharmacy online – mexican pharmacy rohypnol

  21. On April 20th he read of a Cheap Excursion to California with a prevent-above Privilege at each Station and they commenced to read up on Salt Lake and Yellowstone. On May 1st she flashed a Prospectus of a Northern Lake Resort in which Boats and Minnows had been cost-free and Nature was at any time smiling. Same-intercourse associations may possibly be legally regarded in the form of marriage, civil unions, domestic partnerships, or registered partnerships. It also removed the ban on abroad very same-sex marriages becoming recognised in Australia, together with ones that occurred prior to the law modify. Carrie is invited to a couple’s property in the Hamptons only to be flashed by the partner, and Miranda’s law business thinks she’s a lesbian. These actions have drawn notice to gentlemen whose energy commonly shields them from scrutiny-the most noteworthy among the accused arrive from legislation enforcement, politics, and the culture business. Not only had been we dealing with some of the most violent adult males in the nation, on our really doorstep – which we anticipated would occur as soon as we began to offer refuge -but we had some equally violent gals on the inside of, also.

  22. Sheila表示:

    Why Sectional With Pull Out Bed Is A Lot More Dangerous
    Than You Believed l shaped sleeper sectional [Sheila]

  23. Easydrorbix表示:

    legal online pharmacy: top online pharmacy 247 – generic viagra online pharmacy reviews

  24. Drstobeese表示:

    online pharmacy program: Diltiazem – seroquel online pharmacy

  25. seo software表示:

    I have been browsing online more than 3 hours today, yet I never found any interesting article
    like yours. It is pretty worth enough for me. In my opinion, if all website owners and bloggers made good content as you did, the
    net will be a lot more useful than ever before.

  26. I was suggested this blog by means of my cousin. I’m no longer positive whether this publish is written by way of him as no one else understand
    such special about my difficulty. You are wonderful!
    Thank you!

  27. Os ganhos são pagos prontamente e pode ser levantados com precisão para seu conta bancária. venha https://stuartfbrown.com/?p=6730 e tente tudo o que nós fornecemos.

  28. ucdstytft表示:

    EUR USD is the best currency pair to trade. This is because it is the most liquid currency pair and has the lowest spread. Moreover, as a major currency pair, it is available on all forex platforms. Name * Another aspect to look for when evaluating online forex brokers is the educational services offered by them. This helps you to master the art of forex trading. Brokers that provide you with a variety of educational tools for assisting you in assessing the Forex market are the best forex brokers to work with. The RAW Account, on the other hand, is designed for traders aiming for the tightest spreads, starting at zero pips, with a fixed commission fee of $7 round turn. This account is available on the Forex platform and MetaTrader 5 for an experience tailored to high-volume trading. One of the key advantages for beginners at Spredex is its integration with TradingView, a leading financial visualization platform. This integration allows novice traders to access advanced charting tools and perform technical analysis with ease, a feature that is essential for making informed trading decisions.
    https://iris-wiki.win/index.php?title=Broker_en_forex
    Forex and Crypto trading represent two diverse spectrums of the financial world. Forex, also known as foreign exchange or currency trading, centers on the exchange of fiat currencies like the US dollar, Euro, or Japanese Yen. It’s the world’s largest and most liquid market, operating 24 hours a day, five days a week. Traders in the Forex market speculate on the value fluctuations of these currencies, aiming to profit from changes in exchange rates. The Forex market’s liquidity and stability make it a favored choice for many investors, especially those looking to diversify their portfolios. The basic principles that control how the prices fluctuate apply in both types of trading. It’s about supply and demand – if a cryptocurrency coin has more buyers than sellers the price will most likely increase. On the other hand, if there are more sellers than buyers the prices will drop over an extended period of time. That applies to both forex and crypto.

  29. The 10 Scariest Things About Mesothelioma Attorney Mesothelioma Attorney mesothelioma

發佈留言

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