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,363,542 Responses

  1. Taj Stubbs表示:

    17 Signs That You Work With Rolls Royce Replacement Key Rolls Royce Key Replacement

  2. LeroyAcuff表示:

    Профессиональный сервисный центр сервисный центр телефонов ремонт сотовых телефонов

  3. RamonRek表示:

    semaglutide cost: semaglutide online – cheapest rybelsus pills

  4. 9 Things Your Parents Teach You About Cheap Couches For Sale cheap couches for Sale

  5. Ofelia表示:

    5 Killer Quora Answers To Automatic Folding Electric Scooter automatic folding electric scooter, Ofelia,

  6. В магазине сейфов предлагают стоимость сейфа сейф москва

  7. I really love your site.. Very nice colors &
    theme. Did you build this amazing site yourself? Please reply
    back as I’m hoping to create my very own website and would like to learn where you got this from or
    exactly what the theme is called. Cheers!

  8. Sol Bartels表示:

    5 Clarifications Regarding Buy ADHD Medication Uk Remedies For Adhd In Adults

  9. 9 . What Your Parents Taught You About Car Keys Repair repair

  10. Looking For Inspiration? Check Out Upvc Door And Window window locks For upvc

  11. Marcus Simos表示:

    Undeniable Proof That You Need Private ADHD Clinic private adhd assessment west yorkshire

  12. Forrest表示:

    Howdy! Do you know if they make any plugins to assist with Search Engine Optimization? I’m trying to get my blog to rank for some targeted keywords but I’m
    not seeing very good success. If you know
    of any please share. Thank you!

  13. 3 Ways The Automatic Folding Mobility Scooter Near Me Influences Your Life autofold mobility scooter

  14. Julienne表示:

    Hello, every time i used to check web site posts here in the early hours in the
    dawn, because i love to find out more and more.

  15. How To Tell If You’re Ready To Go After Audi A3 Key Replacement audi A3 spare key

  16. 10 Things You Learned From Kindergarden That Will Help You Get Audi Key replacement audi key fob (Stephany)

  17. Don’t Be Enticed By These “Trends” About Key Programming key programmer near me

  18. Nida Hays表示:

    10 Tell-Tale Symptoms You Must Know To Get A New Assessment For Adhd In Adults Adhd assessment for adults near me

  19. LeroyAcuff表示:

    Профессиональный сервисный центр ремонт мобильных телефонов сервис по ремонту телефонов москва

  20. you’re in point of fact a good webmaster. The website loading speed is amazing.

    It seems that you are doing any distinctive trick. In addition, The contents are
    masterpiece. you have done a wonderful job on this subject!

  21. Sammy Riemer表示:

    How Do I Explain Lightweight Electric Wheelchair To A 5-Year-Old invacare Electric Wheelchair (electric-mobility-scooter11100.blogrenanda.com)

  22. Millard Rolph表示:

    Window Repair Aylesbury Tools To Ease Your Everyday Lifethe Only Window Repair Aylesbury Trick Every Individual Should Learn window repair aylesbury (Mozelle)

  23. BarryDof表示:

    https://rybelsus.shop/# buy semaglutide online

  24. Why Nobody Cares About Buggy 2 In 1 Best 2 In 1 Prams 2024

  25. Профессиональный сервисный центр по ремонту планшетов в Москве.
    Мы предлагаем: сколько стоит заменить стекло на планшете самсунг
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  26. Peggy Hockman表示:

    You’ll Be Unable To Guess Situstoto Slot’s Tricks Situstoto Slot

  27. 5 Repair Upvc Door Projects For Every Budget upvc Door handle repair near me; https://postheaven.Net,

  28. Useful info. Fortunate me I discovered your website unintentionally, and I am surprised why this coincidence didn’t
    came about earlier! I bookmarked it.

  29. Jeremypag表示:

    rybelsus cost buy semaglutide online buy semaglutide online

發佈留言

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