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,197,090 Responses

  1. Medicine information for patients. What side effects can this medication cause?
    sumatriptan online
    Everything about medication. Get here.

  2. Medicament prescribing information. Effects of Drug Abuse.
    can i buy clomid without a prescription
    Best information about medication. Get here.

  3. Drug prescribing information. Generic Name.
    can i purchase mobic
    Actual about medication. Read here.

  4. StephenNef表示:

    учебная виза в испанию на год https://vnzh24.ru/

  5. teamae888bet表示:

    Hey, I think your blog might be having browser compatibility issues.

    When I look at your blog in Safari, it looks fine but when opening in Internet Explorer, it has some
    overlapping. I just wanted to give you a quick heads up! Other then that, wonderful blog!

  6. phenq reviews表示:

    Your mode of describing the whole thing in this post is
    truly fastidious, all can without difficulty be aware of it, Thanks a
    lot.

    Feel free to surf to my site – phenq reviews

  7. Всем привет! Подскажите, где почитать разные статьи о недвижимости? Пока нашел https://utc96.ru

  8. plus500表示:

    Wow, superb blog layout! How long have you been blogging for?
    you made blogging look easy. The overall look of your web site is magnificent, as well as the content!

  9. Всем привет! Может кто знает, где почитать полезные статьи о недвижимости? Пока нашел https://utc96.ru

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

  11. porn表示:

    Howdy would you mind sharing which blog platform you’re using?

    I’m looking to start my own blog in the near future but
    I’m having a difficult time choosing between BlogEngine/Wordpress/B2evolution and Drupal.
    The reason I ask is because your layout seems different then most blogs and I’m looking for something completely unique.
    P.S Apologies for being off-topic but I had to ask!

  12. memek cantik表示:

    I’ve read a few good stuff here. Definitely worth bookmarking for revisiting.
    I wonder how a lot attempt you put to create this sort of wonderful informative site.

  13. hacklink表示:

    porn cannibalism

  14. That is really attention-grabbing, You’re an excessively professional blogger.
    I’ve joined your rss feed and look ahead to searching for
    extra of your excellent post. Additionally, I’ve shared your web site in my social networks

  15. my webpage – facebook of sex (http://dongguri.com)

  16. bokep jepang表示:

    Attractive component of content. I simply stumbled
    upon your weblog and in accession capital to assert that I get
    actually loved account your weblog posts. Anyway I will be subscribing on your feeds or even I
    success you get entry to constantly rapidly.

  17. xxx表示:

    homosexual porn

  18. 구글SEO表示:

    Keyword Laddering – An Idea To Success With Serps
    구글SEO

  19. Всем привет! Может кто знает, где почитать разные блоги о недвижимости? Пока нашел https://utc96.ru

  20. Drug information. Cautions.
    can i order dramamine for sale
    Actual trends of medicine. Get information here.

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

  22. video表示:

    Simply desire to say your article is as astounding.
    The clearness in your post is just nice and i could assume you’re an expert on this
    subject. Fine with your permission allow me to grab
    your RSS feed to keep updated with forthcoming post.
    Thanks a million and please carry on the enjoyable work.

  23. Hi! This is kind of off topic but I need some
    advice from an established blog. Is it tough to set up your
    own blog? I’m not very techincal but I can figure things out pretty fast.
    I’m thinking about making my own but I’m not sure where to begin. Do you have any points or suggestions?
    With thanks

  24. hey表示:

    My relatives every time say that I am killing my time here at web, however I know I am getting experience all the time by reading such fastidious articles or reviews.

  25. squirt表示:

    If some one desires to be updated with newest technologies then he must be pay a quick visit
    this web site and be up to date all the time.

  26. Arlen Nizo表示:

    7 Secrets About Collapsible Mobility Scooters
    That Nobody Can Tell You Arlen Nizo

  27. 10 Meetups About Upvc Front Doors Supplied And Fitted Near Me You Should Attend upvc door And Window

發佈留言

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