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,056 Responses

  1. 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.

  2. KennethPah表示:

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

  3. Jayden Henry表示:

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

  4. RobertJar表示:

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

  5. Seriously a lot of great tips!

  6. 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!

  7. 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

  8. 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

  9. 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

  10. KennethPah表示:

    buying prednisone can you buy prednisone over the counter prednisone 30

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

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

  13. Nikefut表示:

    dark web websites deep web drug url darknet markets 2024

  14. 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

  15. RobertJar表示:

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

  16. SamuelBix表示:

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

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

  18. 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

發佈留言

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