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,371,424 Responses

  1. Nam表示:

    What’s The Fuss About Electric Fireplace Freestanding?
    freestanding fireplace – Nam,

  2. RichardNef表示:

    Грузовые шины КАМАЗ вездеход являются одним из самых востребованных видов шин для грузовых автомобилей. Грязевые шины для внедорожников. Все размеры резина aeolus

  3. among us porn表示:

    Diosa introduced me to the CrashPad. I was drawn to the revolutionary act of
    queer/trans POC making queer porn for different queer
    and trans POC.

  4. Frankevild表示:

    https://ozempic.art/# Ozempic without insurance

  5. The Unknown Benefits Of Toto Sites 토토사이트 모음

  6. RamonRek表示:

    ozempic coupon: ozempic coupon – ozempic online

  7. BrianAmese表示:

    Отечественный интернет-магазин “Мебель-шмммммммебель” приглашает широченный круг мебели для кухонь. ЯЗЫК нас вы выкопаете все нужное для тварей уютного и многофункционального внутреннего убранства http://www.tyfapao6kuhnishki.ru/.

  8. Wonderful site. Plenty of helpful info here. I am sending it
    to several buddies ans also sharing in delicious.

    And naturally, thank you to your effort!

  9. kontol表示:

    I am sure this post has touched all the internet
    viewers, its really really fastidious piece of writing on building
    up new website.

  10. Официальный сайт казино Криптобосс:
    ваша удача на расстоянии
    клика онлайн казино криптовалют

  11. Как зайти на Криптобосс через зеркало cryptoboss casino официальный сайт

  12. Jeremypag表示:

    ozempic coupon Ozempic without insurance Ozempic without insurance

  13. Профессиональный сервисный центр по ремонту автомагнитол в Москве.
    Мы предлагаем: ремонт автомагнитол рядом
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  14. 9 Lessons Your Parents Taught You About Bean Coffee Maker Bean Coffee Maker

  15. HaroldBig表示:

    ozempic coupon: ozempic coupon – buy cheap ozempic

  16. HaroldBig表示:

    rybelsus coupon: semaglutide tablets – cheapest rybelsus pills

  17. toto4D表示:

    30 Inspirational Quotes About Togel4d toto4D

  18. Hi there just wanted to give you a quick heads up. The text in your post seem to be running off the screen in Internet
    explorer. I’m not sure if this is a formatting
    issue or something to do with browser compatibility but I thought I’d post to let you know.
    The design look great though! Hope you get the issue resolved soon.
    Many thanks

  19. gocengqq info表示:

    Heya i’m for the first time here. I found this board and I
    find It really useful & it helped me out a lot.
    I am hoping to present one thing back and help others like you helped me.

  20. BarryDof表示:

    http://rybelsus.shop/# rybelsus cost

  21. Jeremypag表示:

    ozempic generic ozempic cost buy ozempic pills online

  22. BarryDof表示:

    https://rybelsus.shop/# semaglutide online

  23. Jeremypag表示:

    ozempic coupon buy ozempic ozempic generic

  24. I do believe all of the ideas you’ve presented to your post.

    They are really convincing and will definitely work.
    Nonetheless, the posts are too short for novices.
    May you please lengthen them a little from subsequent time?
    Thank you for the post.

  25. Audrea表示:

    10 Places That You Can Find Replacing Lost Car Keys Ford ford kuga key fob replacement (Audrea)

  26. Jeremypag表示:

    rybelsus pill semaglutide cost buy rybelsus online

  27. Frankevild表示:

    https://rybelsus.shop/# semaglutide online

  28. Jeremypag表示:

    buy cheap ozempic buy ozempic pills online ozempic generic

發佈留言

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