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,526,856 Responses

  1. unpop.net表示:

    Тhеre’s cеrtainly a great deal to learn ɑbout tһiѕ topic.
    I гeally lkke all of the pointѕ үou made.

  2. Your posts are always on the money. They’re accurate and helpful.

  3. Diplomi_yoel表示:

    купить диплом электрика в нижнем тагиле man-diploms.ru .

  4. Thank you for sharing your info. I really appreciate your efforts and I will be waiting
    for your next write ups thank you once again.
    https://rajapaitowarnahk.com/

  5. Oh my goodness! Impressive article dude! Many thanks, However I am experiencing troubles with your RSS.
    I don’t know why I cannot subscribe to it.
    Is there anybody having the same RSS issues?
    Anyone who knows the solution will you kindly respond?
    Thanks!!

  6. как вызвать наркологическую бригаду https://skoraya-narkologicheskaya-pomoshch-moskva12.ru/ .

  7. Diplomi_lima表示:

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

  8. Diplomi_ztma表示:

    купить диплом в ишиме landik-diploms.ru .

  9. Diplomi_noel表示:

    купить аттестат справку купить аттестат справку .

  10. Having read this I believed it was really enlightening.
    I appreciate you taking the time and energy to put this information together.
    I once again find myself personally spending a significant
    amount of time both reading and posting comments.
    But so what, it was still worthwhile!

  11. Istanbul_vqst表示:

    Подробный обзор Istanbul International Airport, развитие аэропорта на протяжении лет.
    Загадки и тайны Istanbul International Airport, которые вас удивят.
    Особенности проектирования аэропорта, которые невозможно не отметить.
    Планы и развитие Istanbul International Airport, прогнозы и перспективы.
    Сервисы и удобства Istanbul International Airport, какие услуги понравятся каждому.
    new istanbul international airport https://airportistanbulinternational.com/ .

  12. Medicines information for patients. Drug Class.
    order cheap lisinopril online
    Everything information about meds. Get information now.

  13. First off I want to say excellent blog! I had a quick question which I’d
    like to ask if you do not mind. I was interested to know how you center
    yourself and clear your mind before writing. I’ve had a hard time clearing my mind
    in getting my ideas out. I do enjoy writing but
    it just seems like the first 10 to 15 minutes tend to
    be lost just trying to figure out how to begin. Any suggestions
    or hints? Thank you!

  14. Diplomi_htma表示:

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

  15. Seven Explanations On Why Car Keys Cut Is Important Car Key Cutting Near Me Prices

  16. C’est que son assistance clientèle se révèle extrêmement efficace
    et professionnelle.

  17. Diplomi_teel表示:

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

  18. Best SEO Agency 101 The Ultimate Guide For Beginners Seo Agency Hertfordshire

  19. slot表示:

    Currently it sounds like WordPress is the top blogging platform available right now.
    (from what I’ve read) Is that what you are
    using on your blog?

  20. slot表示:

    If you wish for to get a great deal from this paragraph then you have to apply these strategies to your won web site.

  21. Diplomi_yxma表示:

    купить готовый диплом новосибирск landik-diploms.ru .

  22. Istanbul_hdst表示:

    Подробный обзор Istanbul International Airport, развитие аэропорта на протяжении лет.
    Необычные стороны аэропорта, о которых вы не знали.
    Строительство Istanbul International Airport, которые невозможно не отметить.
    Планы и развитие Istanbul International Airport, направления роста и совершенствования.
    Что делает аэропорт уникальным, что сделано для комфорта путешественников.
    new airport istanbul https://airportistanbulinternational.com/ .

  23. best bunk表示:

    Guide To Best Bunk Bed Desk: The Intermediate Guide For Best Bunk Bed Desk best bunk

  24. slot表示:

    Fantastic site. A lot of useful information here. I am sending
    it to a few buddies ans additionally sharing in delicious.

    And of course, thanks on your sweat!

  25. Istanbul_qrst表示:

    Основные моменты Istanbul International Airport, успешные этапы развития.
    Интересные факты о Istanbul International Airport, которые вас удивят.
    Строительство Istanbul International Airport, которые невозможно не отметить.
    Что ждет аэропорт в ближайшие годы, новые горизонты и возможности.
    Что делает аэропорт уникальным, какие услуги понравятся каждому.
    international flights istanbul airport https://airportistanbulinternational.com/ .

  26. Cedric表示:

    From the 1930s to the 1970s, asbestos settlement (Cedric) was extensively employed
    in construction materials. It was put in insulation for
    pipes, fireproofing products cements and plasters, car brakes
    and much more.

發佈留言

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