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,672,004 Responses

  1. Bookmarks表示:

    A Complete Health Club Experience Anywhere, At Any Time.

    Also visit my site: Bookmarks

  2. case revolver表示:

    10 Tips For Will CSGO Case Prices Go Down That Are
    Unexpected case revolver

  3. Real-time exercise tracking overviews your workouts.

    My web site – california fitness equipment for sale

  4. window repair表示:

    11 Ways To Totally Block Your Glass Window Repair window repair

  5. emilyalfab表示:

    Великолепная фраза
    купить диплом Екатеринбург можно через специализированные платформы, которые гарантируют конфиденциальность и безопасность для своих пользователей. Ключевой момент тщательно отбирать провайдера, рекомендации о котором допустимо найти в интернете, чтобы минимизировать опасности.

  6. WilliamRhype表示:

    http://nolvadex.life/# tamoxifen bone density

  7. Real-time workout monitoring guides your exercises.

    Here is my web site Fitness equipment near Me

  8. RandallTaulp表示:

    buy generic propecia: buying generic propecia no prescription – propecia generic

  9. Incredible! This blog looks just like my old one! It’s on a completely different subject but it has pretty much the same page layout and design. Great choice of colors!

  10. Real-time workout monitoring overviews your workouts.

    Also visit my web page; gym equipment near me for sale

  11. WilliamRhype表示:

    http://cytotec.club/# buy cytotec pills

  12. m1bar.com表示:

    10 Books To Read On Replacement Fiat Key fiat punto replacement key – m1bar.com,

  13. RandallTaulp表示:

    get cheap propecia without dr prescription: get propecia online – buy generic propecia no prescription

  14. Davidtes表示:

    lisinopril 10 mg on line prescription zestril 20 mg price lisinopril 40 mg prices

  15. 7 Simple Secrets To Totally Rocking Your Mesothelioma Attorneys asbestos claim

  16. Real-time workout monitoring overviews your exercises.

    my web site – jeff fitness equipment empire

  17. Highly energetic article, I enjoyed that bit.

    Will there be a part 2?

  18. Ronaldpsymn表示:

    https://finasteride.store/# generic propecia price

  19. RandallTaulp表示:

    lisinopril 2.5 mg for sale: lisinopril 15mg – can you order lisinopril online

  20. Davidtes表示:

    clomid nolvadex nolvadex for sale tamoxifen and antidepressants

  21. Real-time exercise tracking guides your exercises.

    Here is my blog used fitness equipment california

  22. Davidtes表示:

    where to buy nolvadex tamoxifen endometrium tamoxifen citrate

  23. WilliamRhype表示:

    http://ciprofloxacin.tech/# buy generic ciprofloxacin

  24. WilliamRhype表示:

    http://lisinopril.network/# lisinopril 20 12.5 mg

  25. pecah5000表示:

    I read this paragraph completely concerning the resemblance
    of most recent and earlier technologies, it’s amazing article.

  26. How To Explain 10kg Load Grade A Washing Machines To Your Grandparents 10Kg Load Washing machine

  27. Hi! I could have sworn I’ve been to this site before but after checking through some
    of the post I realized it’s new to me. Anyhow, I’m definitely glad I found it and I’ll be bookmarking and checking back frequently!

  28. Bookmarks表示:

    A Full Gym Experience Anywhere, At Any Time.

    My blog :: Bookmarks

發佈回覆給「check my reference」的留言 取消回覆

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