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,231,418 Responses

  1. Easydrorbix表示:

    flonase new zealand pharmacy: pharmacy store design layout – uk online viagra pharmacy

  2. Maximo表示:

    What Is ADHD Titration UK’ History? History Of ADHD Titration UK what is adhd titration (Maximo)

  3. brvbqlrve表示:

    If you’ve been an online bingo fan for a while, you’ll have heard about no deposit bingo sites. But are there any no deposit bingo bonuses available? And if “yes,” what do you need to claim them? The latest skill-based bingo app has arrived to the Appstore. Bingo King is giving away thousands of dollars to players every single day. Take your chance to win hundreds in real cash prizes when you compete in ad-free bingo competitions. This website is using a security service to protect itself from online attacks. The action you just performed triggered the security solution. There are several actions that could trigger this block including submitting a certain word or phrase, a SQL command or malformed data. If you’re wondering how you can find a £15 no deposit bonus – the truth is that you need to act quickly. By this, we mean that £15 free no deposit bingo sites typically have a quota – meaning that they can only offer a certain number of bonuses before the offer expires. This does make sense when you consider that the bingo site is effectively giving away free cash without asking for any payment methods or deposited funds.
    https://base-directory.com/listings12816518/https-pokerdom-official-monster-bouncing-ball-8-app
    • Game 1: Knicks 121, Pacers 117 (Knicks lead series, 1-0) Despite the Knicks’ early lead in the series, Joel Embiid remains confident in Philadelphia’s potential. He has boldly stated that the 76ers will still come out on top. The Knicks are -230 to win on Monday, according to DraftKings. “Even going into tonight’s game, I think he was averaging 30 points against Indiana,” Thibodeau said. “Everyone, we’ve all come to expect him to be super-human every night. And he’s in incredible player. He’s loaded up on every night. He’s the focal point of everyone’s game plan. And sometimes it’s a case of missing shots, and they could be good shots. And so I think we all tend to forget that and the thing I love about his approach is he never gets crazy. He’s like a machine every day, he comes in locked in, this is what he’s going to do, he’ll be ready for the next game.”

  4. Just want to say your article is as surprising. The clarity in your post is just cool and
    i can assume you are an expert on this subject. Fine with your
    permission allow me to grab your RSS feed to keep updated
    with forthcoming post. Thanks a million and please keep up the rewarding work.

  5. Wow, marvelous weblog format! How lengthy have you ever been blogging
    for? you made running a blog glance easy. The whole look of your
    web site is wonderful, let alone the content material!

  6. Drstobeese表示:

    Silagra: online pharmacy zyprexa – best online cialis pharmacy

  7. 10 Inspirational Graphics About Mesothelioma Attorney Mesothelioma attorney assistance – https://fromdust.art

  8. Hey I know this is off topic but I was wondering if you knew of any widgets I could add to my blog that automatically tweet my newest twitter updates.
    I’ve been looking for a plug-in like this for quite some time and
    was hoping maybe you would have some experience with something like this.

    Please let me know if you run into anything. I truly enjoy reading your blog and I look forward to your new
    updates.

  9. Learn how表示:

    Greetings from Carolina! I’m bored at work so I decided to browse your
    blog on my iphone during lunch break. I enjoy
    the info you present here and can’t wait to take a look when I get home.
    I’m shocked at how fast your blog loaded on my mobile ..
    I’m not even using WIFI, just 3G .. Anyways, good blog!

  10. I am truly thankful to the owner of this web
    page who has shared this wonderful piece of writing at at this place.

  11. Easydrorbix表示:

    unicare pharmacy artane castle shopping centre: diltiazem online pharmacy – compound pharmacy online

  12. grilled meat表示:

    Does your blog have a contact page? I’m having a tough time locating it but, I’d like to send you an email.
    I’ve got some suggestions for your blog you might be interested in hearing.
    Either way, great website and I look forward to seeing it
    expand over time.

  13. Undeniably imagine that that you said. Your favorite reason seemed to
    be at the internet the easiest factor to have in mind of.
    I say to you, I definitely get annoyed at the same time as people consider issues
    that they just don’t recognise about. You controlled to hit the nail upon the highest as well
    as defined out the entire thing with no need side effect , folks can take a signal.
    Will likely be again to get more. Thanks

  14. shemale fuck表示:

    Please let me know if you’re looking for a writer for your blog.
    You have some really great articles and I think I
    would be a good asset. If you ever want to take some of the load off, I’d love to write
    some articles for your blog in exchange for a link back to mine.
    Please blast me an e-mail if interested. Thank you!

    Take a look at my web page; shemale fuck

  15. If you want to increase your knowledge just keep visiting this site and be updated with the latest news posted here.

  16. Otis表示:

    ADHD Titration: The Ultimate Guide To ADHD Titration titration process
    adhd (Otis)

  17. Asking questions are really good thing if you are not understanding anything completely, but this paragraph gives good understanding yet.

  18. Easydrorbix表示:

    rx pharmacy india: viagra online us pharmacy – diplomat specialty pharmacy lipitor

  19. Easydrorbix表示:

    sands rx pharmacy: percocet price pharmacy – professional pharmacy

  20. I’m impressed, I have to admit. Rarely do I encounter a blog that’s equally educative and
    engaging, and let me tell you, you’ve hit the nail on the head.

    The issue is an issue that not enough people are speaking intelligently about.

    I’m very happy that I found this in my hunt for something concerning this.

  21. Why ADHD Without Medication Isn’t A Topic That People Are Interested In ADHD Without Medication best Medication for anxiety depression and adhd

  22. I just could not depart your web site before suggesting that I actually enjoyed the standard information an individual provide
    to your guests? Is going to be back frequently in order to inspect new posts

    my blog … Ultra K9 Pro Reviews

  23. 9 . What Your Parents Teach You About Clinical Depression Symptoms symptoms Of Clinical depression

  24. Easydrorbix表示:

    low dose naltrexone pharmacy: Apcalis SX – trustworthy online pharmacy

  25. uiqmsdebs表示:

    Discover your rhythm at Seminole Hard Rock Hotel & Casino Tampa. This AAA Four-Diamond-rated hotel features one of the largest casinos in the United States and is home to world-class entertainment and award-winning restaurants. The Pin Up Casino app is packed with virtual table games, and each has a classic theme and different theme variants. Players can enjoy all the games virtually with other users. The platform offers online sports betting options that can please all sports enthusiasts. You have successfully signed up to receive more information from Bally’s Atlantic City Casino Resort.  Pin Up Casino Azerbaijan offers several advantages that make it a standout online gaming platform in the country. Here are five key advantages of choosing Pin Up Casino in Azerbaijan: As a gesture of warm welcome, Pin Up Casino Azerbaijan offers a generous welcome bonus of up to 700 AZN to newly registered players. This bonus provides players with additional funds to explore the vast selection of games available on the platform and enhance their gaming experience.
    https://careers.gita.org/profiles/5171598-dustin-walters
    The inspiration for one of our favorite kids birthday parties comes from the NBC game show “Minute to Win It” and if you have never seen this show- I’ll summarize it for you. Contestants are given challenges involving common household items to complete in 60 seconds to win ever-increasing prize money. So the first challenge will be the easiest one, and they continue to ramp up in difficulty as contestants work their way up to the ultimate $1 million prize. But the best part is that the challenges are fun (and funny!) and can easily be replicated at home for your very own Minute to Win It Birthday Party! No matter what game you choose, all you need for an escape room game is a printable PDF kit, scissors, and some glue. Place the puzzles around your home and let your kids play. You serve the role of the game master, giving them hints as they progress in the game.

  26. Spot on with this write-up, I absolutely believe that
    this website needs a lot more attention. I’ll
    probably be returning to see more, thanks for the advice!

  27. pinup表示:

    Fine way of describing, and nice piece of writing to take facts on the topic of my presentation subject matter,
    which i am going to present in university.

發佈留言

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