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...

903,013 Responses

  1. When it comes to repair of your wardrobe door in Romford,
    you have many options. There are a myriad of options available for repairs
    to your wardrobe bifold doors romford in Romford, from damaged locks to doors falling.

  2. sexy realdoll表示:

    You’ve found the most effective sexdolls. This article will provide information on how
    to decide between a silicone sexdoll and a TPE sexdoll.
    If you are not certain which one you should
    choose take a look at our comparison chart to help you
    choose.

    Also visit my web-site; sexy realdoll

  3. Angelo表示:

    If you’re thinking of purchasing an enlarger penis enlargement pumps (Angelo)
    pump, there are a few things to consider. First, be sure that
    the pump works. Also, read reviews from customers, since some
    pumps pay their customers to write glowing reviews.

  4. People with ADHD are often confused about the differences between the adult and
    child versions. Both are mental health disorders.
    To be diagnosed both adults and children who suffer from treating adhd in adults need to consult an audiologist.

  5. Aveeno Face Defense is a moisturiser moisturisers with Spf a high SPF that comes in many varieties.
    Its SPF is greater, but it also has glycerin, which attracts and holds in water within your skin.

  6. Toasters are great kitchen tools which can be used
    to make delicious breads, bagels and toast. There are different types of toasters to pick from, and you can choose one that
    best suits the way you like to eat your food.

    Also visit my blog … 2 slice long Slot Toaster

  7. There are a variety of options for moisturisers for your face that can help you combat sun damage.
    We’ve examined Paula’s Choice and Eucerin as well as bareMinerals and Nivea SunUV Face
    Shine Control.

    Also visit my blog post :: Moisturiser Spf

  8. If your home electrical repair near me floor box is released in the soil, individuals likely how the box recently been shaken enough
    to break one for the mounting bill. You can fix this using
    a small drill and drill a newer hole directly in software program.

  9. Mental health表示:

    It isn’t easy to find the right treatment for a mental
    disorder. The best option is talking to your physician or mental health provider in an excellent way to express your emotions and develop strategies for dealing with it.

  10. Many retailers are entering the Delta 8 gummies blue razz
    8 space. However, with so many products on the market, it can be difficult to determine which are of the best quality.

  11. double glazing Repairs watford repairs to the glazing in Watford
    require the expertise of professionals who can quickly and efficiently deal
    with any job.

  12. games表示:

    Online poker is legal. However, you must ensure that
    you’re legal. Most online poker sites require players to be 18 years old or at
    least the legal drinking age for your area
    of residence.

    Have a look at my page; games

  13. Sally can be a smart woman suffering from ADD. She had a difficult
    experience at school, did not achieve very good grades,
    and was repeatedly told she was lazy, but she persisted.

    Here is my web page :: Adult Adhd Assessments

  14. If you’ve lost or misplaced your car keys, you can count on the
    services of an auto automotive locksmith near me (nakhonchaisi.go.th) to duplicate keys for
    you. These professionals specialize in transponder keys, remote keys,
    and various other modern key types.

  15. The quick Short term loan term
    loan is a convenient option to manage a situation in your financial situation. It can also be an easy
    solution to deal with an unexpected bill, however, it should not
    be used to pay off an enormous debt burden.

  16. When it comes to selecting the most appropriate Nespresso Coffee Machines coffee maker There are a
    variety of models available. Here’s a brief look at the VertuoLine OriginalLine, Essenza
    Mini and VertuoNext. You can also read more about VertuoNext and.

    Lattissima.

  17. What’s mental health? It’s How To Get A Mental Health Assessment state of mind that is unaffected from
    harmful or negative behaviors. It doesn’t matter if a sufferer has an illness of the mind or physical illness.

  18. If you’re in search of CBD dog treats, it’s good to know that there are options close to you.
    There are numerous businesses that sell top-quality Cbd dog treats near Me
    products online. If you’re looking for full-spectrum co2 extract,
    then PET CURE has you covered.

  19. Bets表示:

    You can choose the theme you like and play hundreds of online slots.
    While the payouts could differ however, they all adhere to the same mathematical formula.
    To find the ideal slot game for you, search for the “Auto Spin” option.

    Here is my web-site; Bets

  20. It can be a real pain to find your car locked out.
    But don’t be worried! Auto locksmiths with experience can assist you in getting back on the road as soon as possible.

    Feel free to visit my blog – automotive locksmith near me

  21. If you’re in the market for some new sexually explicit toys, you may like to look into Overkink the online Sex store retailer for
    sex toys that was founded by Jaycee Chester in 2018.

  22. There are many varieties of marijuana best cbd Edibles available for purchase.
    These products allow you to consume cannabis without the legal risks and restrictions that come with
    smoking.

  23. If you are suffering with a mental disorder and are
    seeking assistance, you may think about consulting a Private psychiatrists near me psychiatrist in London. They are specially trained to treat psychiatric disorders and specialize in mental health.

  24. There are a variety of ways to get a Short Term loan bad Credit loan even with bad credit.
    Some lenders will grant small loans of only several hundred dollars and others provide up to
    five thousand dollars.

  25. Are you in search of an adult toy Websites toy store near
    me? New York is the most populous megacity in the
    world, with an estimated population of 8.6 millions and an urban area of
    more than 20 million.

  26. There are a number of things you should keep in mind when purchasing a
    Penis Enlargement Pumps Online enlarger pumps.
    First, make sure that the pump is efficient. Also, you should
    read customer reviews since some pumps will offer customers money to write
    glowing reviews.

  27. item451038401表示:

    Wonderful beat ! I would like to apprentice whilst
    you amend your site, how can i subscribe for a blog site?
    The account aided me a appropriate deal. I were
    tiny bit familiar of this your broadcast provided vivid transparent idea.

    Feel free to surf to my web-site: item451038401

  28. van Security表示:

    To ensure your van security, you can fit locks on both the rear and
    front doors. They can also be put on the side doors that slide in the event that your vehicle has one.
    You can lock this type of lock using a single key.

  29. It is crucial to take into consideration the various aspects when purchasing a
    small Wood burning Stove (http://Aural.online/)-burning stove.

    There are many things to think about before making an investment.

    Whatever you decide to buy, you will be happy with the
    outcomes.

  30. The purchase of a tiny double Small.Double mattress can be a daunting task if your not sure which features to search for.
    We will take a look at the advantages and disadvantages of buying
    one.

發佈留言

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