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,363,620 Responses

  1. Sazrqjz表示:

    Диплом техникума купить официально с упрощенным обучением в Москве
    fotomaniya.getbb.ru/viewtopic.php?f=16&t=13561

  2. Sazreow表示:

    Полезные советы по безопасной покупке диплома о высшем образовании

    domkodeks.ru/question/ofitsialnyj-diplom-bez-lishnih-usilij-prosto-i-bystro

  3. การอธิบายชัดเจน ทำให้เข้าใจได้แม้ไม่มีพื้นฐาน

  4. ขอบคุณที่ให้ข้อมูลเชิงลึกและมุมมองที่แตกต่างครับ

  5. เป็นบทความที่ชัดเจนและตรงประเด็นดีมากค่ะ

  6. Philipabusa表示:

    Заправка картриджей для принтеров и МФУ в Донецке: быстро, качественно, доступно!

  7. Nikefut表示:

    deep web markets tor market url https://darknetmarketstore.com/ – onion market

  8. We stumbled over here by a different web address and thought I may as well check
    things out. I like what I see so now i am following you. Look forward to exploring your web page yet again.

  9. вызов нарколога на дом краснодар dubna.myqip.ru/?1-5-0-00000282-000-0-0-1730730082 .

  10. Have you ever thought about including a little bit more than just
    your articles? I mean, what you say is fundamental and
    all. However just imagine if you added some great images or videos to
    give your posts more, “pop”! Your content is excellent but with pics and video
    clips, this site could undeniably be one of the very best in its field.
    Terrific blog!

    My web site; omegle alternatives

  11. электрокарнизы купить в москве электрокарнизы купить в москве .

  12. LeonardKnism表示:

    flowers777.ru/ — Качественные кухни с гарантией от производителя.

  13. BrandenSlomy表示:

    purchase prednisone: cheap prednisone – buying prednisone mexico

  14. Thanks for sharing your thoughts on togel4d. Regards

  15. электрокарнизы москва elektrokarniz495.ru .

  16. stem cell表示:

    You can certainly see your expertise in the article you write.
    The arena hopes for even more passionate writers such as you who aren’t afraid to mention how they believe.
    All the time follow your heart.

    Look into my web page stem cell

  17. Miguel Phelps表示:

    I dropped my phone last week and thought it was done for! Thankfully, I found a great repair service that helped me out iphone repair

  18. Hеllo would you mind letting me know ѡich hosting
    company you’re utilizing? I’ve loaded your blߋg in 3 compⅼetely
    different wweb browsers and I must say this blog loads a lot faster then most.
    Can you recommend a good web hostinng provider at a fair price?

    Сheers, I appreciawtе it!

    My webpage Top 10 mẫu đồng hồ nữ bán chạy nhất hiện nay

  19. spam site表示:

    Have you ever considered about including a little bit more
    than just your articles? I mean, what you say is
    important and everything. However just imagine if you added some great photos or video clips
    to give your posts more, “pop”! Your content is excellent
    but with images and videos, this website could certainly be one of
    the greatest in its field. Fantastic blog!

發佈留言

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