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,418,026 Responses

  1. Timsothyabela表示:

    Keep on writing, great job!
    best online casinos

  2. Bezomealved表示:

    Мне срочно понадобились деньги на лекарства, а пенсия будет только через неделю. Соседка подсказала Telegram-канал Займы без отказа на карту. Зашла, нашла удобный список займов, где дают всем без отказов. Отправила заявку в пару компаний, деньги пришли за 10 минут. Лекарства купила, и даже осталось немного на продукты.

  3. Jim Wheeler表示:

    Construir redes apoyo mutuo permite superar obstáculos juntos gener Dinámicas grupales

  4. Everyone loves it whenever people get together and share
    thoughts. Great website, continue the good work!

  5. Dereketerm表示:

    max pharm: dapoxetine price – priligy

  6. BrandenSlomy表示:

    priligy maxpharm: max pharm – buy priligy max pharm

  7. 5 Killer Quora Answers To Replacement Key For Audi A3 Replacement Key
    For Audi A3; https://G2827265.Ziblogs.Com,

  8. Asking questions are genuinely pleasant thing if you are
    not understanding something entirely, but this piece of writing gives
    pleasant understanding even.

  9. BrandenSlomy表示:

    how to get generic clomid: generic clomid – can i get clomid no prescription

  10. Gregory Hale表示:

    I lately partnered with a electronic advertising and marketing firm, and the results have been useful! If you’re looking for knowledgeable support, check out Local SEO for a few splendid insights

  11. mosbet oyunu表示:

    biz/ uzmanlarımız/ deneyimli geliştiricilerimiz {{internet| çevrimiçi | sanal} {kumarhane | kumar evi| oyun alanımızı{kullanıcıların | oyuncuların} isteklerini dikkate alarak hazırladık|geliştirdik |icat ettik} ve {çabalıyoruz |.

    Feel free to visit my web-site :: https://mostbetgiriss.com/

  12. Nikefut表示:

    blackweb dark market onion https://darknetmarketstore.com/ – darknet seiten

  13. Dereketerm表示:

    dapoxetine online: buy priligy – buy priligy max pharm

  14. Dereketerm表示:

    priligy max pharm: priligy maxpharm – priligy max pharm

  15. Blakesmema表示:

    tort-dubr.ru — Узнайте больше о наших кухнях и услугах на сайте.

  16. LeonardKnism表示:

    кухня заказать – Простая и быстрая возможность заказать кухню вашей мечты.

  17. I don’t even understand how I finished up here,
    but I believed this post used to be great. I don’t
    know who you’re however definitely you are going to a well-known blogger in case you are not already.
    Cheers!

  18. Drug prescribing information. Long-Term Effects.
    buying cheap cozaar online
    Actual what you want to know about pills. Get here.

  19. BrandenSlomy表示:

    max pharm: buy priligy – buy priligy max pharm

  20. Dereketerm表示:

    can you buy prednisone over the counter in usa: Prednisone Without Prescription – 3000mg prednisone

  21. StevenNub表示:

    cost of amoxicillin 875 mg: Amoxicillin for sale – amoxicillin 500mg price in canada

  22. Nikefut表示:

    dark web sites darknet drug market https://darknetmarketstore.com/ – darkweb marketplace

  23. StevenNub表示:

    order prednisone online no prescription: ray pharm – prednisone otc price

  24. My family all the time say that I am wasting my time here at net, but I know I am getting know-how daily by reading
    thes fastidious articles.

  25. WengToto表示:

    I think thіs is аmong the most vital іnformation fоr me.
    And i’m glad reading yоur article. But ᴡant to remark on few ցeneral things, The web site style iѕ great, thhe articles іѕ
    reallpy excellent : D. Goodd job, cheers

    Нave a ⅼooҝ at my pаge :: WengToto

發佈留言

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