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,572,865 Responses

  1. Nearest Edge表示:

    Hi there, just became aware of your blog through Google, and found that
    it is really informative. I am going to watch out for brussels.
    I will be grateful if you continue this in future.
    Numerous people will be benefited from your writing. Cheers!

  2. Arthurhow表示:

    https://indiamedfast.shop/# online medicine shopping in india
    77 canadian pharmacy

  3. LIGACAPSA99表示:

    Every weekend i used to pay a quick visit this web page, as i wish for enjoyment, as this this
    web page conations in fact nice funny material too.

  4. JamesGag表示:

    Mexican Pharm Inter: reliable mexican pharmacies – Mexican Pharm Inter

  5. I visited multiple websites however the audio feature
    for audio songs existing at this site is really superb.

  6. Rudolfalgok表示:

    visit their website zkLogin

  7. JamesGag表示:

    online medicine shopping in india: online medicine shopping in india – online medicine shopping in india

  8. 1v1lol.me表示:

    Іt’s the best time to make some ρlans for the futuгe and it is time to
    be happʏ. I have read this post and if I could I desirе to ѕjggeѕt you few interesting things
    or tips. Perhas you can write next artidⅼes referring tо this article.
    I wiszh to гead even more things abokut it!

    Herе is my webb site: 1v1lol.me

  9. thetawallet表示:

    Hello There. I found your blog using msn. This is an extremely well
    written article. I will make sure to bookmark it and come
    back to read more of your useful information. Thanks for the post.

    I will definitely return.

發佈留言

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