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,374,410 Responses

  1. Tony Buchanan表示:

    Had a magnificent enjoy with my remaining order from nang tanks ! Highly propose them

  2. Nicely put, Thank you!

  3. bookmarked!!, I love your blog!

    My blog post :: Abogado penalista Barcelona

  4. Olivia Howell表示:

    The dedication of Moseley Collins Law to fighting for clients’ rights after accidents is commendable—keep up the great work! Moseley Collins Law

  5. Why No One Cares About All Crypto Casinos online casino Deposit bonus

  6. Victor Guzman表示:

    It’s refreshing to read a post that highlights both sides of the argument when it comes to deciding between buying or leasing office equipment; very well done top rated copier service

  7. Saved as a favorite, I really like your site!

  8. Jessetor表示:

    Получайте кэшбэк до 5% на каждый покупку с картой Сбербанка! Экономьте на покупках в магазинах, кафе и онлайн. Простое оформление и удобное управление через мобильное приложение.
    Начните экономить уже сегодня!======>
    Дебетовая карта Детям в Жуковском

  9. Lina Perez表示:

    Great job on this article; it’s so important to find a reliable shop like how I found out about car body shop

  10. Hard Times Gambling Tips To Make Money 에볼루션 바카라 불법 (https://ai-db.science/)

  11. homepage表示:

    Great information, Thank you!

  12. JacobLoody表示:

    nemakrame.ru/ – стильные решения для вашего кухонного пространства.

發佈留言

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