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,247,972 Responses

  1. Dereketerm表示:

    how to get generic clomid pill: cheap clomid – can you get generic clomid prices

  2. BrandenSlomy表示:

    price of prednisone 5mg: generic Prednisone – cheap prednisone online

  3. Dereketerm表示:

    prednisone 60 mg price: buy prednisone – buy 40 mg prednisone

  4. Markdob表示:

    Всем привет! Может кто знает, где найтиполезные блоги о недвижимости? Пока нашел – https://enrubattery.ru

  5. You are so cool! I don’t suppose I’ve read something like that before.
    So great to discover someone with genuine thoughts on this issue.

    Really.. many thanks for starting this up. This website is something that is required on the web, someone with a little originality!

  6. BrandenSlomy表示:

    dapoxetine online: priligy maxpharm – Priligy tablets

  7. Markdob表示:

    Приветствую. Может кто знает, где найтиполезные статьи о недвижимости? Пока нашел – https://enrubattery.ru

  8. StevenNub表示:

    amoxicillin without a prescription: Amoxicillin buy online – buy amoxicillin online uk

  9. Although some may still see love dolls for a taboo or controversial matter, エロ 人形there are various explanation why They may be a beneficial addition to fashionable Modern society.

  10. JamesIncew表示:

    Предлагаем вам высококачественный тротуарный бордюр – идеальное решение для обрамления дорожек, газонов, цветников и других элементов ландшафтного дизайна.
    Наш тротуарный бордюр отличается прочностью, долговечностью и устойчивостью к воздействию внешних факторов, что делает его идеальным выбором для любых условий эксплуатации – [url=https://seoms.nucelo.co/articles/bruschatka-trotuarnaya-vybor-dlya-gorodskoj-infrastruktury]брусчатка тротуарная[/url]

  11. Dereketerm表示:

    where can i buy clomid without insurance: rex pharm – buy clomid no prescription

  12. StevenNub表示:

    where can i buy cheap clomid without prescription: cheap clomid – how can i get cheap clomid

  13. Nikefut表示:

    drug markets onion best darknet markets https://darknetmarketstore.com/ – free dark web

  14. StevenNub表示:

    buy generic clomid without dr prescription: rex pharm – clomid buy

  15. Dereketerm表示:

    priligy max pharm: priligy – max pharm

  16. gerçek fon için bahis yok:% 100 eğlence,% 0 risk içinde https://mostbetturki.com/! Bu inanılmaz sıradışı oyun hepinizi şaşırtacak | şaşırtacak | memnun edecek.

發佈留言

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