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

503,868 Responses

  1. Website表示:

    Excellent website. Plenty of useful information here. I am sending
    it to a few buddies ans additionally sharing in delicious.
    And obviously, thanks for your sweat!

  2. whoah this blog is excellent i really like reading your posts.

    Keep up the great work! You know, a lot of individuals are looking
    round for this information, you can aid them greatly.

  3. betting表示:

    There are many different rules and regulations that govern online gambling.
    For instance, in the US it is not possible to have gambling websites that
    are located in your country of residence. However, it is possible to be set up elsewhere.

    My webpage betting

  4. Window Pros of georgian doors enfield is the local company that can carry out repairs to
    double glazing. They have years of experience installing secondary double glazing on Grade 2 structures which includes churches.

  5. Local locksmiths in Enfield window repairs will have
    a good knowledge of the region and can be with you in less than 30 minutes.
    They are able to assist you in an emergency and provide valuable advice.

  6. Hello, its nice paragraph regarding media print, we all be
    familiar with media is a fantastic source of information.

  7. casino表示:

    Gambling online has gained popularity over the last
    decade. In 1996, there were just fifteen websites. In 1997 there
    were more than 200 websites. In 1998 an Frost & Sullivan report
    stated that online gambling brought in $830 million of revenue.

    Also visit my blog; casino

  8. MichaelNep表示:

    deep web drug store dark market

發佈留言

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