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,245,218 Responses

  1. This is a great tip especially to those fresh to the blogosphere.

    Short but very precise info… Appreciate your sharing this one.
    A must read article!

  2. Medicine information for patients. What side effects can this medication cause?
    order cheap verapamil no prescription
    All information about meds. Read here.

  3. giro messeri表示:

    Wonderful article! This is the type of info that are meant
    to be shared across the internet. Shame on Google for not
    positioning this submit upper! Come on over and consult with my web site .
    Thanks =)

  4. StevenNub表示:

    prednisone 40 mg daily: prednisoneraypharm – cheap prednisone 20 mg

  5. BrandenSlomy表示:

    prednisone uk: prednisone ray pharm – can i buy prednisone online without a prescription

  6. Blakesmema表示:

    http://north-web.ru — Узнайте больше о наших уникальных решениях для кухни.

  7. Dereketerm表示:

    where to buy prednisone without prescription: ray pharm – prednisone 10mg prices

  8. slot demo表示:

    Everything is very open with a precise explanation of the challenges.
    It was definitely informative. Your website is very useful.

    Many thanks for sharing!

  9. Fantastic blog! Do you have any tips for aspiring writers?
    I’m hoping to start my own site soon but I’m a little lost on everything.
    Would you recommend starting with a free platform like WordPress or go for a paid option? There are so many options out there
    that I’m totally confused .. Any ideas? Thanks a lot!

  10. I’m extremely impressed along with your writing skills
    and also with the layout in your blog. Is that this a
    paid subject matter or did you customize it your self?
    Either way stay up the excellent high quality writing, it is rare to look a great weblog like this one nowadays..

  11. This is a topic that is close to my heart… Take care!
    Exactly where are your contact details though?

    https://awppgh.com/

  12. Тут можно преобрести оружейные сейфы купить купить шкаф для оружия

  13. BrandenSlomy表示:

    can you get clomid without dr prescription: clomid online – can i get cheap clomid tablets

  14. Content-Spinning.fr est une plateforme qui vous aide à générer rapidement des contenus optimisés et de qualité. Produire du contenu uniques et de qualité devient plus rapide et plus facile.

  15. lgo4d表示:

    Today, while I was at work, my sister stole my iPad and tested to see
    if it can survive a forty foot drop, just so she can be a youtube sensation. My iPad is now destroyed and she has 83 views.
    I know this is entirely off topic but I had to share it with someone!

  16. situs toto表示:

    Hello there, just became alert to your blog through Google,
    and found that it’s truly informative. I’m gonna watch out for brussels.

    I’ll be grateful if you continue this in future.

    Lots of people will be benefited from your writing.
    Cheers!

  17. Nikefut表示:

    deep web drug store tor dark web https://darknetmarketstore.com/ – darknet marketplace

  18. Тут можно преобрести сейф для оружие цена сейфа для оружия

  19. Aw, this was a very good post. Taking a few minutes and actual effort to create a very good article…
    but what can I say… I put things off a lot and never
    manage to get nearly anything done.

  20. iProInvestor表示:

    I’m really enjoying the design and layout of your website.
    It’s a very easy on the eyes which makes it much more enjoyable for me to come here and visit more often. Did you hire out a designer to create your theme?

    Excellent work!

  21. StevenNub表示:

    how much is prednisone 10 mg: prednisoneraypharm – prednisone daily use

  22. 티비위키表示:

    hi was just seeing if you minded a comment. i like your website and the thme you picked is super. I will be back 티비위키

  23. BrandenSlomy表示:

    amoxicillin 500mg capsules price: buy amoxil online – amoxicillin 500mg price in canada

  24. MatthewNib表示:

    Why this small city is the ‘eyeglasses capital’ of Japan
    [url=https://omgto3.com]omg сайт[/url]
    Japan is famed for its skilled artisans, masters who maintain a commitment to tradition while modernizing production techniques in line with the development of new materials and processes.

    Many places in the country have grown famous by focusing on specific crafts, from exquisite kimonos to perfectly designed knives. Among them is the small city of Sabae, in Fukui prefecture, about a 3.5-hour train ride from Tokyo.
    https://omgto3.com
    омг вход
    It’s widely known as Japan’s eyeglasses capital – and for good reason. Sabae produces over 90% of the frames manufactured in the country, according to the local government. Signs and objects shaped like eyeglasses can be found on city streets, and there’s even a museum and festival devoted to spectacles.
    The art of making spectacles
    Sabae, located on Japan’s main Honshu island near the city of Fukui, has been producing quality eyewear for more than a century.

    It all started in 1905, when a local government official invited skilled eyeglasses artisans to come to the city to teach their craft, an attempt to create new opportunities for local farmers.

    The move paid off. Today, Sabae has over 100 companies that collaborate to make pairs of glasses.

    Though these studios use cutting-edge machinery to produce new frames made of metal and acetate, most stages still require the skilled hands and trained eyes of Sabae’s master artisans.

    That includes Takeshi Yamae, a frame designer with Japanese brand Boston Club who has lived in the city for 17 years. He tells CNN one pair of glasses can involve more than 200 steps.

    “I first design it, sketch it, then put it into my computer,” he says. “From the time I start designing, to the time I have the perfect product, it takes more than a year.”

發佈留言

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