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

  1. KennethFom表示:

    בשביל סוג כזה של בילוי; יש בהן מיטה נוחה עם מצעים נקיים לבילוים פרועים, מקלחת, שירותים, מזגן וכל מה שצריך. דירות דיסקרטיות וכל מילה מדוברת נעשים על מנת לחרמן את הגברים. הנשים המפתות של דירות דיסקרטיות ברמת גן חיות בשביל לאהוב. הבנות האלה לא רק מאירות נערת ליווי דירה דיסקרטית בשירות פרטי

  2. 5 Clarifications Regarding Online Shop Designer Suits {Toto Cst423Ef (https://vimeo.com/)

  3. pipe bomb diy表示:

    I have read some good stuff here. Certainly worth bookmarking for revisiting.
    I wonder how so much effort you place to make this sort of great informative website.

  4. I wanted to thank you for this wonderful read!! I certainly loved every little bit of it.
    I’ve got you bookmarked to check out new things you post…

  5. PIZZA PIZZA PIZZA слот – это увлекательный слот,
    разработанный для тех, кто любит азарт и вкусную пиццу.
    Дизайн игры и символы на барабанах пропитаны атмосферой итальянской кухни и создают неповторимое настроение.
    Погрузитесь в космос вкусной и азартной игры с слотом PIZZA PIZZA PIZZA 2.Запустите барабаны:
    Нажмите кнопку Спин и дождитесь остановки
    барабанов. 1.Выберите ставку: Установите желаемую ставку на
    линию и численность линий, на которые вы хотите поставить.

    Как играть в PIZZA PIZZA PIZZA ?

  6. Five Killer Quora Answers On Online Shopping
    Uk Women’s Clothing Online Shopping Uk

  7. pipe bomb diy表示:

    I have read so many articles on the topic of the blogger lovers but this piece of writing is really a pleasant piece of writing, keep it up.

  8. 17 Reasons Why You Should Not Ignore Uk Online Shopping Sites
    For Electronics Lifetime Warranty Network Switch

  9. The Top Companies Not To Be In The Jackpot Slots Industry top jackpot slots (shinyoungwood.co.kr)

  10. Diplom_cnKl表示:

    купить диплом бакалавра https://ukr-diplom.ru .

  11. Diplom_byKl表示:

    купить диплом в самаре купить диплом в самаре .

  12. Drugs information for patients. Short-Term Effects.
    where to get generic zofran without dr prescription
    Some information about drugs. Read information here.

  13. 5 Killer Quora Answers To Popular Casino Slots popular casino slots

  14. When I originally commented I clicked the “Notify me when new comments are added”
    checkbox and now each time a comment is added I get four e-mails with the same comment.
    Is there any way you can remove me from that service?
    Appreciate it!

  15. dương vật表示:

    Magnificent site. Lots of helpful information here.
    I am sending it to several buddies ans also sharing in delicious.

    And naturally, thanks on your sweat!

  16. This paragraph is genuinely a nice one it helps
    new internet people, who are wishing for blogging.

  17. The Three Greatest Moments In Slot Jackpots
    History progressive jackpot slots

  18. Can I simply just say what a comfort to find somebody who
    actually understands what they’re discussing on the web.
    You certainly know how to bring an issue to light
    and make it important. More and more people ought to look at this and understand
    this side of your story. I was surprised you aren’t more popular because you certainly have the
    gift.

  19. door Repair表示:

    Window Repair Luton 101 This Is The Ultimate Guide For Beginners
    door Repair

  20. Hi! Someone in my Facebook group shared this website with us so I came to look it over.

    I’m definitely enjoying the information. I’m book-marking and will be tweeting
    this to my followers! Outstanding blog and terrific design and style. https://Visualchemy.gallery/forum/profile.php?id=4011195

  21. free slots表示:

    The 10 Scariest Things About Free Slots free slots

  22. Jogue no cassino aprovado Blaze

  23. I know this web site offers quality depending articles or reviews and additional stuff, is there any other web site which presents these kinds of things in quality?

  24. Fela Lawyer表示:

    Where Will Fela Claims Railroad Employees One Year From What Is Happening Now?
    Fela Lawyer

  25. The 10 Scariest Things About High Roller Slots high roller slots – mybookmark.Stream

  26. undress ai表示:

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

  27. slot sites表示:

    Why Do So Many People Would Like To Learn More About Real Money Slots?

    slot sites

  28. Highly energetic post, I enjoyed that bit. Will there be a part 2?

  29. sell drugs表示:

    When I initially commented I clicked the “Notify me when new comments are added” checkbox and now each time a comment is
    added I get several emails with the same comment. Is there any way you
    can remove people from that service? Cheers!

  30. It’s amazing to visit this web page and reading
    the views of all colleagues about this paragraph, while I am
    also eager of getting experience.

發佈留言

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