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...

840,881 Responses

  1. Rickysem表示:

    reputable mexican pharmacies online mexico pharmacies prescription drugs buying prescription drugs in mexico

  2. Michaelcew表示:

    http://mexicoph24.life/# mexican online pharmacies prescription drugs

  3. Cortney表示:

    Pay Attention: Watch Out For How Semi Truck Attorney Is Taking Over And What Can We Do About It semi truck accidents – Cortney,

  4. Smog check表示:

    Thank you a lot for sharing this with all of us you
    really recognise what you are speaking about!
    Bookmarked. Please also visit my web site =). We can have a hyperlink trade arrangement between us

  5. How Cerebral Palsy Settlement Influenced My Life For The
    Better cerebral Palsy Lawsuit

  6. “The Ultimate Cheat Sheet” On Sofa Sets For
    Sale modern Couches for Sale

  7. Result SDY表示:

    Hey there would you mind letting me know which webhost
    you’re working with? I’ve loaded your blog in 3
    different web browsers and I must say this blog loads a lot faster then most.
    Can you suggest a good web hosting provider at
    a honest price? Thanks, I appreciate it!

  8. Truly tons of useful information!

  9. Ten Upvc Window Repairs That Really Change Your Life Upvc Window repairs

發佈留言

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