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,249,855 Responses

  1. Nice weblog here! Additionally your website loads up fast!
    What web host are you using? Can I am getting your affiliate link for your host?

    I want my site loaded up as quickly as yours lol

  2. Kolyaska_zyPl表示:

    Идеальная коляска Bugaboo для вашего малыша, Bugaboo – это не просто коляска, это инвестиция в комфорт и безопасность, Почему мамы выбирают коляски Bugaboo, Какие преимущества у колясок Bugaboo, Bugaboo: легкость и управляемость в каждом краше, Bugaboo Cameleon: легендарная коляска для малышей, Bugaboo Bee: стиль и удобство для малыша, Bugaboo Runner: коляска для активных мам.
    бугабу для двойни купить бугабу для двойни купить .

  3. AlbertDuM表示:

    buy cytotec pills online cheap: buy cytotec online – buy cytotec over the counter

  4. DarrenUnjuh表示:

    https://iverfast.com/# minocycline pill

  5. PASARANTOGEL表示:

    Today’s Gacor Togel Market is the best choice for players who are looking for big winning opportunities and trusted services.https://racksandbaskets.com/

  6. AlbertDuM表示:

    buy misoprostol over the counter: cyt premium – buy cytotec in usa

  7. Предлагаем услуги профессиональных инженеров офицальной мастерской.
    Еслли вы искали сервисный центр lg, можете посмотреть на сайте: сервисный центр lg в москве
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  8. AlbertDuM表示:

    cheapest Lisinopril: Lisinopril 1st – Lisinopril 1st

  9. DarrenUnjuh表示:

    https://plavixclo.com/# Cost of Plavix without insurance

  10. doyok168 slot表示:

    This is my first time pay a visit at here and i am actually happy to
    read everthing at one place.

  11. Drugs information for patients. Long-Term Effects.
    where can i buy ampicillin pill
    Best trends of drug. Read now.

  12. Very nice post. I just stumbled upon your weblog and
    wished to say that I’ve really enjoyed browsing your blog posts.
    In any case I’ll be subscribing to your feed and I hope you write again soon!

  13. выведение из запоя воронеж стационар ekonomimvmeste.ukrbb.net/viewtopic.php?f=14&t=65373 .

  14. вывод из запоя в стационаре анонимно alhambra.bestforums.org/viewtopic.php?f=2&t=46417 .

  15. fully furnished is not necessary an important factor

  16. Polly Diaz表示:

    Planning a trip can be overwhelming desert safari dubai

  17. doyok168 slot表示:

    If you want to improve your know-how simply keep visiting this web site and be updated with the newest gossip posted here.

  18. Stanton Hymel表示:

    property malaysia to buy

  19. macauslot88表示:

    I have read so many articles on the topic of the blogger lovers but this post
    is in fact a good paragraph, keep it up.

發佈留言

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