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

805,806 Responses

  1. While Mental health near me health problems can be difficult to overcome, they are possible to
    be overcome. In order to have a positive recovery, it’s essential to seek out treatment at
    an early stage.

  2. pnbct.in表示:

    Cleaning dolls that are real doll Sexdoll, pnbct.in, isn’t
    simple. They must be thoroughly cleaned, especially
    when they have openings. They shouldn’t be cleaned with chemicals or bleach.
    Be sure to clean them thoroughly to prevent the growth
    of mold.

  3. ADHD is an often challenging disorder. The most effective way
    to deal with it is to locate an ADHD clinic close to me.
    They offer a range of services and treatments to help individuals deal with the challenges of dealing with Adhd Psychiatrists Near Me.

  4. temperament表示:

    The Myers-Briggs Type Test is a scientific test that can assist you
    to identify the job or profession you desire. By knowing your personality type, you can identify a profession that you will love and one that will be rewarding
    and relaxing.

    Here is my web-site :: temperament

  5. The sleek spaceship that houses the Panasonic bread 4 Slice Toaster White, which
    is four slices wide, is made of stainless steel . It has a sleek glossy
    casing. The slots that can be adjusted in width make
    it possible to accommodate all bread types.

  6. There are two main kinds of CBD E-liquid which are refillable
    and disposable. Vape pens that are disposable require no refill and can be disposed of when they’re empty.
    Refillable Cbd Vape Juice E-liquids can be filled and can hold anywhere from 1.0
    to 1.

  7. There are three pores and skin attention deficit disorder – inattentive, hyperactive-impulsive,
    and effectiveness of 2.

    Feel free to visit my page :: assessments for adhd In adults

  8. If you are searching for a cheap toaster on sale be sure to take a few factors into consideration. Size, warranty, price,
    and quality are just some of the things to think about.

  9. It is recommended to contact a locksmith emergency locksmith Near my Area service
    if you are locked out. These professionals offer 24 hour locksmith services to solve your
    lockout issues.

  10. There are numerous aspects to take into consideration when selecting the best folding scooter.
    A Folding scooters mobility
    scooter should be lightweight and durable so it won’t be affected by rain.

  11. There are many different types of moisturisers that have spf moisturiser for Men,
    but if you want a high SPF that is bouncy and bouncy it
    is recommended to try Aveeno Face Defense.

  12. You might be enticed by the low-cost delta-8 delta8 hemp flower shop.
    However, this can have serious drawbacks. Cheap flowers can be sloppy
    in quality and offer poor customer service.
    Be sure to select brands with a strong emphasis on customer service.

  13. You’ve found the right place should you be in search of a new toaster.
    This article will provide information on the various models of toaster which
    include the Smart Long Slot toaster 2 slice with Infrared radiation as well as the Compact toaster.

  14. A locksmith near me emergency can be
    a great asset to any homeowner or business. These experts can enhance the
    security of your property and safeguard your valuables.

    They are also able to unlock security safes and repair different types of locks.

  15. Are you struggling to make ends meet? Payday loans loan online payday
    offer many benefits. Fast approval with no credit check flexible repayment options,
    secured against valuables, and many more features. Find out how you
    can apply today for one of these loans.

  16. While male adhd In women Adults symptoms typically
    include disruptive behaviors like hyperactivity, hyperactiveness, and impulse
    control, signs of ADHD for women are more subtle. Anxiety and low self-esteem are common among women. They can be difficult to detect.

  17. Solution – You will need test your battery during this scenario.
    A simple way to take might be to just switch on interior
    Mobile Car Lock Repair lights.

  18. Automotive keys today are integrated with security
    features, almost eliminating the odds of any theft. With a smart key Reprogramming, may do prevent
    your automobile from being stolen, even if the thieves find a way to break
    when.

  19. You’ve come to the right place If you’re looking for a moisturizing moisturizer moisturiser with spf 50 50.

    Sunny Daze SPF50 Moisturizer provides both UVA and UVB protection, and is rich in vitamin E and zinc oxide.

  20. Hopefully, you’ll find the job that is effective with your ADD, and we’ve stated
    that before in other articles. Good jobs for anyone with attention deficit
    include jobs that have lots of diversity because ADD people
    do get bored easily.

    Here is my blog; Iam Psychiatry

  21. Cheap Pet cbd表示:

    Cheap Pet cbd for pets is a safe
    treatment for dogs with the same balancing and restorative properties as humans.
    You can purchase CBD capsules for oil, CBD oil tinctures, chewy snacks
    as well as CBD oil tinctures in a variety of forms.

  22. WilliamTraug表示:

    https://buynolvadex.store/# should i take tamoxifen

  23. ktzfokzn表示:

    where to buy hydroxychloroquine otc hydroxychloroquine 200mg buy buy hydroxychloroquine 200 mg

  24. You’ve come to the right spot If you’re looking for an spf moisturiser for face 50 moisturizer with moisturizing properties.
    The Sunny Daze SPF 50 Moisturizer has both UVA and
    UVB protection and is a rich source of vitamin E and zinc oxide.

  25. It is recommended to speak with an holistic veterinarian when searching for Buy Cbd Cat Treats
    for cats. These professionals are trained to understand the advantages
    of CBD for cats and provide suggestions and recommendations for
    your pet.

  26. acheter lsd表示:

    It’s an remarkable paragraph in support of all the internet people; they will get benefit from it I am sure.

  27. ADHD is a serious illness which can create a variety of difficulties in everyday life.
    The doctor may prescribe medication to help manage
    Adhd Specialist Near Me symptoms, or suggest
    alternative therapies that can enhance your everyday living skills.

  28. If you’re seeking a scent that is not too feminine You may want
    to try the MCM Eau de Parfum. This scent is inspired from the mythological water element.

    Here is my webpage Unisex perfume

  29. If you’re looking for a nutritious SPF 50 moisturiser with spf 50 for your skin,
    you’ve come to the right spot. The Sunny Daze SPF 50 Moisturizer
    offers both UVA and UVB protection and a rich source of vitamin E and
    zinc oxide.

發佈回覆給「spf moisturiser for face」的留言 取消回覆

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