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,155,883 Responses

  1. Danieldob表示:

    Приветствую. Подскажите, где почитатьразные блоги о недвижимости? Пока нашел https://tent44.ru

  2. How To Ship To Ireland From Uk Tools To Streamline Your Daily Lifethe One How
    To Ship To Ireland From Uk Trick That Everyone Should Be Able To how to Ship to ireland From uk

  3. Ten Things You Learned About Kindergarden To Help
    You Get Top Single Strollers best Single jogging Stroller (https://forum.Everleap.com/)

  4. Pills information sheet. Cautions.
    can i buy cheap pioglitazone price
    Everything about medication. Read here.

  5. I love your blog.. very nice colors & theme. Did you make
    this website yourself or did you hire someone to do it for you?

    Plz answer back as I’m looking to design my own blog and would like to find out where u
    got this from. kudos

  6. Terri表示:

    Factor well applied..

  7. t=aboutBook表示:

    Wonderful blog! Do you have any helpful hints for aspiring writers?
    I’m hoping to start my own website 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 choices out there that I’m completely overwhelmed ..
    Any recommendations? Cheers!

  8. CLICK HERE表示:

    Hi there just wanted to give you a quick heads up. The words in your
    post seem to be running off the screen in Internet explorer.

    I’m not sure if this is a format issue or something to do with web browser compatibility but
    I figured I’d post to let you know. The design look great though!
    Hope you get the issue resolved soon. Thanks

  9. How To Recognize The Motor Vehicle Lawyers That’s Right For You Motor Vehicle Accident Lawsuits

  10. BomesJoype表示:

    Lorem Ipsum has been the industry’s standard dummy text https://mjoelnirsseite.de/awnxuyc of type and scrambled it to make a type specimen book.

  11. I blog often and I really appreciate your content.
    This great article has really peaked my interest.
    I’m going to bookmark your website and keep checking for
    new information about once per week. I opted in for your Feed as well.

  12. Hey there would you mind stating which blog platform you’re working with?

    I’m looking to start my own blog soon but I’m having a hard time selecting between BlogEngine/Wordpress/B2evolution and Drupal.

    The reason I ask is because your design and style seems different then most blogs and I’m looking for
    something unique. P.S Sorry for being off-topic but I had to
    ask!

  13. You’ll Never Guess This Online Shopping Uk Amazon’s Benefits Online Shopping Uk Amazon

  14. Danieldob表示:

    Приветствую. Может кто знает, где найтиполезные блоги о недвижимости? Сейчас читаю https://tent44.ru

  15. 789nexia表示:

    You really make it appear really easy together with your presentation but I find
    this topic to be actually one thing that I feel I’d never understand.

    It sort of feels too complex and very huge for me.
    I’m taking a look forward to your subsequent publish, I’ll attempt to get the dangle of it!

  16. TAMPUNG99表示:

    Hey There. I discovered your weblog using
    msn. This is a really well written article. I’ll
    make sure to bookmark it and return to read more of your helpful information. Thanks for the post.

    I’ll definitely comeback.

  17. You’ll Never Guess This Malpractice Lawyers’s Secrets malpractice lawyer

  18. online game表示:

    You should be a part of a contest for one of the greatest blogs on the internet.
    I’m going to recommend this website!

  19. akartoto表示:

    WOW jᥙst ѡhɑt I was ⅼooking for. Cɑme here by searchibg fօr How tο find whats trending tⲟday?

    My web blog: akartoto

  20. Нарушение этих и любых других правил может привести к блокированию аккаунта.

  21. The 10 Most Terrifying Things About 3 Wheel Mobility Scooter For Adults 3 Wheel Mobility Scooter For Adults

  22. Guide To Upvc Doors Luton: The Intermediate Guide In Upvc Doors Luton Upvc doors luton

  23. 10 Things Everybody Gets Wrong About The Word “Erb’s Palsy Claim” erb’s Palsy lawsuit

  24. Verona表示:

    You could certainly see your enthusiasm in the article
    you write. The sector hopes for more passionate writers like you who aren’t afraid to mention how they believe.
    All the time go after your heart.

發佈留言

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