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

848,263 Responses

  1. WilliamRhype表示:

    http://lisinopril.network/# lisinopril without prescription

  2. 10 Meetups On Repair Upvc Window You Should Attend
    Upvc window repairs

  3. Davidtes表示:

    generic propecia without insurance propecia without a prescription order propecia for sale

  4. RandallTaulp表示:

    lisinopril brand name cost: lisinopril 40 mg price – lisinopril 2 mg

  5. WilliamRhype表示:

    http://lisinopril.network/# lisinopril 1 mg

  6. 10 Ways To Create Your CS GO Case New Empire Revolution Case

  7. Davidtes表示:

    propecia propecia brand name propecia without prescription

  8. Three Of The Biggest Catastrophes In Double Glazed Units Manufacturers
    Near Me History Double Glassing

  9. 15 Best Private ADHD Assessment UK Bloggers You Should Follow Best private Adhd Assessment uk

  10. I really like what you guys are up too. This type of clever
    work and reporting! Keep up the amazing works guys I’ve included
    you guys to our blogroll.

  11. 7 Small Changes That Will Make An Enormous
    Difference To Your Shopping Online Uk Multi-Purpose Steam Cleaner

  12. Leslieprerm表示:

    Лечение от мефедрона https://krasnodar-narkolog.ru/

  13. RandallTaulp表示:

    cipro 500mg best prices: buy cipro – buy cipro online without prescription

  14. Hi all, here every person is sharing such know-how, so it’s good to read this web site, and I used to pay a visit
    this webpage daily.

    Also visit my blog :: Forex trading technical setups

  15. It’s The Ugly Facts About Repair A Window Window Repairs

發佈留言

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