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,433,983 Responses

  1. Autumn表示:

    This is really fascinating, You are an overly skilled blogger.

    I’ve joined your feed and look forward to searching for extra of
    your fantastic post. Additionally, I have shared your site
    in my social networks

  2. Yоu hɑvе remarked ѵery interesting pointѕ! ps decent
    site.

    Μy blog post – beds for sale online

  3. Isabell表示:

    %%

    my blog post :: jon zherka bio (Isabell)

  4. womens表示:

    %%

    Visit my web site; womens

  5. Gregg表示:

    %%

    Also visit my homepage: full spectrum cbd tincture (Gregg)

  6. OHS表示:

    Wonderful article! That is the kind of info that should be shared around the web.
    Disgrace on Google for not positioning this publish upper!
    Come on over and talk over with my site . Thank you =)

  7. Adelaide表示:

    %%

    Here is my blog: full spectrum cbd oil 1500mg; Adelaide,

  8. Ramonita表示:

    It Is The History Of railroad cancer lawsuit (Ramonita) Lawsuit Multiple Myeloma In 10 Milestones

  9. cadplm.co.kr表示:

    %%

    Feel free to visit my webpage … saab replacement Keys (cadplm.co.kr)

  10. Francisca表示:

    %%

    My homepage :: bosch side by side fridge freezer – Francisca

  11. I have to thank you for the efforts you have put in writing
    this website. I really hope to view the same high-grade content
    by you later on as well. In fact, your creative writing
    abilities has motivated me to get my own blog now 😉

  12. %%

    my web site – What Is Broad-Spectrum Cbd
    Used For (https://Sciencewiki.Science/)

  13. MelisaMum表示:

    покерок сайт
    https://forum.kreit.ru/member.php?u=4454
    PokerOK – это платформа, которая говорит “да” вашим амбициям и страсти к победе. Скачайте клиент PokerOK и войдите в уникальный мир tурниров, акций и бесконечных возможностей. Это ваш шанс стать частью элитного покерного сообщества, где каждая игра – шаг к завоеванию вершины.Так что, если вы готовы к вызову и хотите окунуться в захватывающий мир покера, PokerOK — ваш надежный спутник в этом приключении. Скачайте клиент, присоединяйтесь к столам и докажите, что именно ваша рука достойна звания королевской!

  14. Shana表示:

    mesothelioma payment (Shana)

  15. This is a topic which is near to my heart… Thank you!
    Where are your contact details though?

發佈留言

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