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,367,390 Responses

  1. вызов нарколога на дом круглосуточно ya.7bb.ru/viewtopic.php?id=14601 .

  2. I pay a visit everyday some websites and sites
    to read articles, however this weblog provides quality based content.

  3. Excellent post. I will be facing many of these issues as well..

    Here is my webpage; stem cell treatment

  4. Exceptional post! The role of back links in SEO marketing can’t be ignored. They are crucial for developing authority and enhancing rankings. For a lot more on this subject, take a look at search engine optimization company

  5. sv88表示:

    sv88 vegas

  6. Great delivery. Solid arguments. Keep up the great spirit.

  7. вызов нарколога на дом круглосуточно [url=http://chesskomi.borda.ru/?1-8-0-00003045-000-0-0-1730729839]http://chesskomi.borda.ru/?1-8-0-00003045-000-0-0-1730729839[/url] .

  8. карнизы электрические карнизы электрические .

  9. Helⅼo! Would you mind if I ѕhare уour blog with my twittedr groսp?
    Theгe’s a lot of people that I think would really appreciate your cοntent.
    Please let me know. Thanks

    Here is my web site Top 10 mẫu đồng hồ nữ bán chạy nhất

  10. электрические карнизы электрические карнизы .

  11. Drugs information for patients. Long-Term Effects.
    is buspirone hcl safe
    Some information about medicines. Read information now.

  12. карнизы для штор с электроприводом карнизы для штор с электроприводом .

  13. DerekWab表示:

    кухня на заказ в спб – отличный способ получить интерьер вашей мечты с учетом всех пожеланий.

發佈留言

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