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,124,147 Responses

  1. Quality content is the important to be a focus for the users to pay a quick visit
    the web page, that’s what this site is providing.

  2. 15 Things Your Boss Would Like You To Know You Knew About Adhd
    Assessment Uk How Do I Get An Adhd Assessment, https://Altlifewiki.Com/Index.Php/User:ColemanApodaca4,

  3. Hey there! I realize this is kind of off-topic however I needed to ask.
    Does building a well-established blog like yours require a lot of work?
    I’m brand new to running a blog but I do write in my journal everyday.

    I’d like to start a blog so I can share my personal experience and thoughts online.
    Please let me know if you have any ideas or tips for new aspiring bloggers.
    Appreciate it!

    My web site; how to take prodentim

  4. The Most Sour Advice We’ve Ever Heard About Get Diagnosed With ADHD How Do You Get A Diagnosis Of Adhd

  5. Easydrorbix表示:

    clotrimazole uk pharmacy: mexican online mail order pharmacy – synthroid target pharmacy

  6. togel sydney表示:

    Five Lessons You Can Learn From Situstoto Slot togel sydney

  7. Если вы искали где отремонтировать сломаную технику, обратите внимание – профи тех сервис челябинск

  8. 5 Arguments Robot Vacuum With Mop Is Actually A Beneficial Thing
    Best Robot With Mop

  9. Drstobeese表示:

    inderal pharmacy: online pharmacy reviews klonopin – mexican pharmacies

  10. porn表示:

    online casino

  11. mostbet表示:

    These are really enormous ideas in on the topic of blogging.
    You have touched some good points here. Any way keep up wrinting.

  12. You need to be a part of a contest for one of the best sites on the web.
    I will recommend this blog!

  13. Drstobeese表示:

    oxybutynin online pharmacy: seroquel xr online pharmacy – clonidine pharmacy

  14. Tokenizer360表示:

    Everything is very open with a very clear explanation of the challenges.
    It was definitely informative. Your site is very useful.
    Thanks for sharing!

  15. Easydrorbix表示:

    sumatriptan pharmacy: reputable viagra online pharmacy – unicare pharmacy dublin artane castle

  16. bgshseqjd表示:

    PayPal is a favorite payment method for both players and casinos. As such, it’s available at most US online casinos (aka PayPal Casinos USA). Look at the toplist to pick from the best PayPal sites to play at. Remember Me As a result, operators restrict the number of games valid & playable for the deposit-free bonus. It’s crucial to go through the whole of terms associated with online casino deposit-free bonus in America for a better understanding of its usage. If at all the casino do not feature your best-loved game, do ensure to give this American-based deposit-free bonus a trial. Why Paypal..? The list on this page shows a selection of high quality Paypal casinos – but it is not a complete list of all the sites that accept Paypal. To make sure we recommend only the most reputable, reliable, and trustworthy PayPal casinos, we put each of them through a robust and rigorous review process. Our reviewers use real PayPal accounts and make real money deposits and withdrawals through them, as that is the only way to truly assess how good a certain PayPal casino really is. Every casino that makes our top-rated list must meet strict criteria which include:
    https://wiki-burner.win/index.php?title=Casino_via_paypal
    Tonight's winning Lotto numbers are: 13 – 29 – 36 39 – 44 – 56, and the Bonus Ball is: 3 Could tonight’s jackpot of £4million see you handing in your notice, jetting off to the Bahamas or driving a new Porsche off a garage forecourt? Type in your Powerball numbers to check your ticket! Drawings at 9 P.M. Wednesday & Saturday The estimated jackpot for the drawing on July 15 is worth $875 million. The winning Thunderball numbers were 03, 11, 18, 24, 39 – and the Thunderball was 02. Tonight's winning Lotto numbers are: 13 – 29 – 36 39 – 44 – 56, and the Bonus Ball is: 3 Mega Millions draws five white balls from one machine, with the machine containing one ball for each number 1 through 70. A separate machine contains gold “bonus” balls, marked with numbers 1 through 25. The estimated jackpot for tonight’s Powerball drawing is $900 million and while no one has won the biggest prize in 37 consecutive drawings, three big Wisconsin Powerball winning tickets were sold this weekend.

  17. Drstobeese表示:

    online rx pharmacy: pharmacy cialis generic – safe online pharmacy reviews

  18. Easydrorbix表示:

    online pharmacy no prescription needed klonopin: prescription without a doctor’s prescription – best online pharmacy advair

  19. Если вы искали где отремонтировать сломаную технику, обратите внимание – сервисный центр в челябинске

  20. srasurvivors表示:

    It’s actually a nice and useful piece of information. I am satisfied that you
    simply shared this helpful info with us. Please stay us up to date like
    this. Thank you for sharing.

  21. wilqvwfzb表示:

    Wolves and Chelsea go head-to-head in the U17 Premier League Cup final at Molineux on Thursday evening. TRY A QUIZ: Can you name every Chelsea player to score 20+ Premier League goals? The Portugal international has returned to Stamford Bridge. Watch his best moments for Chelsea from the 2022 23 season Subscribe to Si Phillips Talks Chelsea to keep reading this post and get 7 days of free access to the full post archives. Again, the fact that Enzo Fernandez, Romeo Lavia and Kiernan Dewsbury-Hall are included as a trio bodes well for their probable involvement vs City. Will Mykhailo Mudryk and Noni Madueke respectively start again considering Raheem Sterling, Christopher Nkunku and Cole Palmer are all available once more? Home Partners of America and A New Path to Homeownership are registered trademarks of Home Partners of America LLC.
    https://aprelium.com/forum/profile.php?mode=viewprofile&u=boydhartanklaw1984
    The San Antonio Spurs are in the rumor mill once again, this time being linked to Cam Johnson of the Brooklyn Nets. Parsons, who just became the third Dallas defender to make the Pro Bowl each of his first three seasons, has half a sack in the past three games. The 2021 NFL Defensive Rookie of the Year has never gone four games without at least one full sack. Parsons, who just became the third Dallas defender to make the Pro Bowl each of his first three seasons, has half a sack in the past three games. The 2021 NFL Defensive Rookie of the Year has never gone four games without at least one full sack. For a reasonable $7 a month, in-market fans can catch Cowboys games on NFL+. There’s a significant caveat, however, as games only can be streamed on a mobile device and the game must be of the local or primetime variety. NFL+ will be of no use to Cowboys fans who are out of market.

  22. Если вы искали где отремонтировать сломаную технику, обратите внимание – профи ремонт

  23. Hi there! This article could not be written any better!
    Going through this post reminds me of my previous roommate!
    He continually kept preaching about this. I most certainly will send this article to him.

    Fairly certain he’s going to have a very good read.
    Thanks for sharing!

  24. Reuben表示:

    You’ve Forgotten Vintage Leather Couch: 10 Reasons
    Why You No Longer Need It tufted leather sofa (Reuben)

  25. Land Rover Spare Key: 10 Things I’d Like To Have Known Earlier land Rover Discovery 1 key fob programming

  26. 12 Companies Setting The Standard In Mesothelioma Claim mesothelioma lawyers

  27. Easydrorbix表示:

    pharmacy mall online reviews: griseofulvin online pharmacy – gabapentin pharmacy prices

  28. pinap表示:

    What’s up, this weekend is pleasant in support of me, since this point
    in time i am reading this enormous informative article here at my house.

  29. bokep kontol表示:

    I’m not sure why but this site is loading very slow for me.

    Is anyone else having this problem or is it a issue on my end?
    I’ll check back later and see if the problem still exists.

  30. Drstobeese表示:

    tesco pharmacy products viagra: advair mexican pharmacy – sam’s club pharmacy viagra price

發佈留言

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