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

843,877 Responses

  1. Bets表示:

    There are many reasons to get involved in sports betting.
    From the possibility of making an income, to the excitement and the chance to root for your
    team of choice, to the overall viewing experience.

    Here is my web-site … Bets

  2. Tritype test表示:

    %%

    Also visit my blog; Tritype test

  3. EdgarMak表示:

    dark web sites links deep dark web

  4. Bennett表示:

    There are numerous advantages for playing online poker.
    It is easy to play, and there are no waiting lists and no
    second-hand smoking. You can also play a wide range of games
    (Bennett).

  5. Experience表示:

    There are many options for treatment for addiction to gambling.
    Some of them include one-on-one counseling, medication, and lifestyle changes.
    This can turn into an addiction if you are unable to stop yourself from engaging in it.

    my page: Experience

  6. Saved as a favorite, I love your website!

    Also visit my website Buy Cocaine Online

  7. Lamont表示:

    %%

    Feel free to visit my website; jelly hash cbd; Lamont,

  8. EdgarMak表示:

    darknet drug store tor darknet

  9. Georgebog表示:

    dark web market list dark web sites

  10. Joni Cook表示:

    Merely wanna tell that this is very helpful, Thanks for taking your time to write
    this.

    Also visit my homepage … metal building manufacturers

發佈留言

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