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

  1. LeroyBak表示:

    indian pharmacy paypal India pharmacy delivery indian pharmacies safe

  2. BrandonSaisy表示:

    purple pharmacy mexico price list: mexican pharmacy – mexican drugstore online

  3. see this here表示:

    For most up-to-date news you have to pay a quick visit the web and on world-wide-web I found this site as a best site for hottest
    updates.

  4. I am really impressed together with your writing abilities and also
    with the layout on your weblog. Is that this a paid topic or did you customize it yourself?

    Either way stay up the excellent high quality writing, it is uncommon to see a nice blog like this one today..

  5. Lazrswa表示:

    Купить диплом о среднем полном образовании, в чем подвох и как избежать обмана?
    saturn.forumex.ru/viewtopic.php?f=19&t=283

  6. Williamagric表示:

    ed meds https://mexicanpharm24.cheap/# mexican border pharmacies shipping to usa

  7. Guide To Window Misting Repair: The Intermediate Guide On Window Misting Repair window
    misting repair (https://lovewiki.faith/wiki/15_Reasons_Not_To_Be_Ignoring_Misty_Windows)

  8. As a person that’s constantly been cautious regarding my
    blood glucose, discovering Sugar Defender has actually been a relief.
    I feel so much a lot more in control, and my current examinations
    have shown favorable enhancements. Knowing I have a dependable supplement to support my routine offers
    me assurance. I’m so happy for Sugar Defender’s effect on my wellness!

  9. BrandonSaisy表示:

    top 10 online pharmacy in india: Indian pharmacy worldwide delivery – top 10 pharmacies in india

  10. Thank you a bunch for sharing this with all people you really recognize what you’re
    speaking approximately! Bookmarked. Please also discuss with my website =).
    We will have a link exchange agreement between us

  11. DevonPhack表示:

    https://pharm24.pro/# shots for ed
    ed devices

  12. forn japan表示:

    What’s up to all, the contents present at this website are in fact amazing for
    people knowledge, well, keep up the good work fellows.

  13. Why You Should Concentrate On Improving Truck
    Accident Best Truck Accident Lawyers

  14. The 10 Most Terrifying Things About Mesothelioma
    Lawsuit mesothelioma (https://rayonend5.bravejournal.net)

  15. LeroyBak表示:

    best ed treatments cheaper medications best price for generic viagra on the internet

  16. Williamagric表示:

    injections for ed http://mexicanpharm24.cheap/# mexican online pharmacies prescription drugs

  17. Dedra表示:

    10 Things You Learned In Kindergarden That Will Help
    You Get Fabric Two Seater Sofa two seater fabric sofa, Dedra,

  18. A Good Rant About Lost Car Keys Replacement lost car Key what to do

  19. Howdy fantastic blog! Does running a blog like this require a large amount of work?
    I have virtually no understanding of programming however I had been hoping to start my own blog in the near
    future. Anyway, if you have any suggestions or techniques for new blog owners please share.
    I understand this is off topic but I just wanted to ask.
    Appreciate it!

  20. Clarkwer表示:

    Свой магазин НашаМебель призывает широченный запас кухонь, коие помогут сделать устроенность и комфорт в течение вашем семействе http://notahye4kuhnishki.ru/.

  21. Williamagric表示:

    erectile dysfunction pills http://mexicanpharm24.cheap/# mexico drug stores pharmacies

  22. 5 Clarifications On Automatic Fold Up Mobility
    Scooter automatic folding Mobility Scooter

  23. Why Senseo Coffee Machine Isn’t A Topic That People Are Interested In. senseo coffee maker

  24. DevonPhack表示:

    https://indianpharm24.pro/# best online pharmacy india
    over the counter erectile dysfunction pills

發佈留言

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