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,366,527 Responses

  1. Hi, everything is going fine here and ofcourse every one is sharing facts, that’s in fact excellent, keep up
    writing.

  2. We’re a gaggle of volunteers and opening a new scheme in our community.
    Your web site provided us with helpful info to work on.
    You have done an impressive activity and our entire group shall be thankful to you.

  3. KennethPah表示:

    prednisone 30 mg daily prednisone uk price prednisone 5 50mg tablet price

  4. Jayden Henry表示:

    Appreciate the comprehensive advice. For more, visit decorative concrete austin

  5. RobertJar表示:

    prednisone tablets 2.5 mg: canadian online pharmacy prednisone – price of prednisone 5mg

  6. Seriously a lot of great tips!

  7. 789win91 com表示:

    789win là cổng game cá cược hàng đầu với hàng loạt game hấp dẫn, thưởng lớn và tỷ
    lệ thắng cao. Tham gia ngay để nhận những ưu đãi cực khủng
    từ 789win!

  8. Thanks for the auspicious writeup. It if truth be told used to be a enjoyment account it.
    Glance complex to far brought agreeable from you!
    By the way, how can we keep up a correspondence?

    Also visit my web-site … assisted living facilities

  9. I am sure this paragraph has touched all the
    internet people, its really really pleasant piece
    of writing on building up new blog.

    Here is my blog :: memory care units

  10. Calvin表示:

    Thanks for your marvelous posting! I certainly enjoyed reading it, you coulod be a great author.
    I will be sure to bookmark your blog and will often come back iin the future.
    I want tto encoirage you continue your great posts, have a nice
    weekend!

    my web blog Calvin

  11. KennethPah表示:

    buying prednisone can you buy prednisone over the counter prednisone 30

  12. вывод из запоя на дому в краснодаре вывод из запоя на дому в краснодаре .

  13. Планируете поездку на Байкал? На сайте туры-на-байкал.рф вы сможете подобрать всё необходимое для незабываемого отдыха. У нас доступно более 75 предложений отдыха, включая лучшие авторские туры на байкал зимой для любого. Наш простой в использовании сервис позволяет быстро найти подходящее предложение, будь то быстрая экскурсия или длительный отдых на неделю. Вы легко подберёте туры на любые финансовые возможности — от бюджетных туров до особых предложений всё включено.

  14. Nikefut表示:

    dark web websites deep web drug url darknet markets 2024

  15. I was recommended this blog by my cousin. I am not sure whether this post
    is written by him as nobody else know such detailed about my difficulty.
    You are incredible! Thanks!

    my web-site … senior memory care facilities

  16. RobertJar表示:

    ciprofloxacin 500 mg tablet price: buy cipro online without prescription – ciprofloxacin generic

  17. SamuelBix表示:

    buy cipro online usa: cipro ciprofloxacin – ciprofloxacin 500mg buy online

  18. This Is The Myths And Facts Behind Car Key Repair repair car remote control key

  19. plinko demo表示:

    I could not resist commenting. Exceptionally well written!

  1. 2024-12-23

    what does levitra do

    what does levitra do

  2. 2024-12-23

    finasteride india pharmacy

    finasteride india pharmacy

發佈留言

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