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,524,340 Responses

  1. slot gacor表示:

    I do not even understand how I ended up right here, but I assumed this submit used to be good.
    I do not understand who you’re but definitely you are going to a famous blogger in case you aren’t already.

    Cheers!

  2. Zenitbet表示:

    Хотите иметь доступ к любимым ставкам в любое время? Тогда вам стоит бк зенит скачать! Это приложение предлагает все функции, которые вам нужны для комфортного беттинга. Удобный интерфейс, быстрый доступ к ставкам и возможность следить за результатами в реальном времени делают этот сервис отличным выбором для любителей спорта.

  3. LeroyBak表示:

    mexico drug stores pharmacies mexican drugs mexican border pharmacies shipping to usa

  4. Hi there, I check your blogs like every week. Your writing style is awesome, keep doing what you’re doing!

  5. The Most Worst Nightmare About 4d Result Sport Toto Come To Life 메이저사이트 순위

  6. 11 Methods To Totally Defeat Your Mesothelioma Asbestos Lawyers Mesothelioma lawsuit

  7. BrandonSaisy表示:

    mexico drug stores pharmacies: Legit online Mexican pharmacy – purple pharmacy mexico price list

  8. Do You Know How To Explain Mystery Box To Your Boss
    Open Online Mystery Boxes

  9. Jorgeagopy表示:

    buy medicines online in india: India pharmacy international – world pharmacy india

  10. LeroyBak表示:

    india pharmacy mail order Best Indian pharmacy top online pharmacy india

  11. 10 Wrong Answers To Common Volvo V50 Key Questions Do
    You Know The Correct Answers? volvo key Fob programming near me

  12. LeroyBak表示:

    mexican pharmaceuticals online Mexican pharmacy ship US pharmacies in mexico that ship to usa

  13. This text is invaluable. Where can I find out more?

  14. I think this is among the most important info for me.
    And i am glad reading your article. But should remark on few general things, The website style is
    perfect, the articles is really nice : D. Good job, cheers

  15. Company表示:

    14 Questions You Might Be Anxious To Ask Double Glazing Suppliers Near Me Company

  16. Diplomi_wpel表示:

    купить диплом о высшем образовании в иркутске man-diploms.ru .

  17. Who Is The World’s Top Expert On Psychiatrist Assessment?
    psychiatric Assessment Online

  18. This Is The Ugly Reality About Private Diagnosis Of
    ADHD Adhd Assessment Leeds Private

  19. Williamagric表示:

    what is the best ed pill http://indianpharm24.pro/# Online medicine order

  20. Best Sites For Tiered Link Building 101:”The Complete” Guide For Beginners Tiered linking

  21. CuanToto表示:

    This design іs incredible! Уou defiitely кnow how to keep a reader amused.
    Between уour wit ɑnd yoսr videos, I was almost moved t᧐
    start mу own blog (wеll, almoѕt…HaHa!) Fantastic
    job. І really loved what yoս hɑd to sаy, ɑnd more than that,
    һow you pгesented it. Τoo cool!

    Review mү webpage: CuanToto

  22. slot gacor表示:

    It’s difficult to find experienced people for this topic, however, you
    seem like you know what you’re talking about! Thanks

  23. Jorgeagopy表示:

    medication from mexico pharmacy: mexico pharmacy cheap – mexico pharmacies prescription drugs

  24. LeroyBak表示:

    indian pharmacies safe Pharmacies in India that ship to USA Online medicine home delivery

  25. Diplomi_bqel表示:

    образование купить диплом старая man-diploms.ru .

發佈留言

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