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,678,683 Responses

  1. Michaelscoob表示:

    Clom Fast Pharm: how to buy generic clomid online – Clom Fast Pharm

  2. BrianTom表示:

    zithromax over the counter buy zithromax online cheap zithromax online usa

  3. Excellent write-up. I certainly appreciate this website.
    Stick with it!

  4. Sazrahu表示:

    Мы изготавливаем дипломы психологов, юристов, экономистов и прочих профессий по приятным ценам.– diplomp-irkutsk.ru/kupit-diplom-magistra-s-provodkoj-bistro-i-nadezhno-2/

  5. скупка золота лома b-gold.ru http://www.of-md.com/jwe-qs// .

  6. Hello there! This is my 1st comment here so I just wanted to give a quick shout out and tell you I genuinely enjoy reading through your posts.
    Can you suggest any other blogs/websites/forums that deal with the same topics?
    Thanks a ton!

  7. At first Fu-Fu finds his lessons a bit odd, but his coaching pays off, particularly when Sagwa is in need
    of assist. You won’t require a physician’s help most often nevertheless, it’s best to all
    the time seek the advice of a doctor if it is the first time your baby faces the situation, it becomes unnaturally painful or does not heal shortly and leads to fever along with rashes.
    Small feels sleepy. However, there isn’t a time for sleeping when there’s
    a customer to be served. In a rollover, however,
    your old firm makes the check out to you. Some use a gradual scale where you get to maintain 25 p.c of matching funds
    for annually with the company. The daily or life stage necessities keep
    on changing at every ascending, and each vital life stage of your pet.
    Some could skip the crawling stage altogether and go straight to pulling themselves
    up and cruising alongside holding onto furniture then walking.
    She was then forged in the Channel four soap opera Hollyoaks, portraying
    the role of Sinead O’Connor between 2010 and 2015, and once more from
    2018 to 2019. In 2016, she was the runner-up in the seventeenth
    sequence of Celebrity Large Brother.

  8. Danieldrymn表示:

    where can i buy generic clomid without dr prescription: order generic clomid – Clom Fast Pharm

  9. Danieldrymn表示:

    Pred Pharm Net: Pred Pharm Net – Pred Pharm Net

  10. Richardaudit表示:

    http://zithpharmonline.com/# zithromax capsules 250mg

  11. Richardaudit表示:

    http://amonlinepharm.com/# amoxicillin 500mg price in canada

  12. Richardaudit表示:

    https://predpharmnet.com/# Pred Pharm Net

  13. Sazrrax表示:

    Мы можем предложить дипломы любой профессии по выгодным тарифам.– diplomnie.com/kupit-diplom-s-provodkoj-3/

  14. Richardaudit表示:

    http://lisinexpress.com/# Lisin Express

  15. get lisinopril without dr prescription lisinopril hydrochlorothiazide 10mg 12.5 mg lisinopril hydrochlorothiazide zestoretic
    lisinopril 10 mg look like order generic lisinopril online how to get generic lisinopril prices
    can you get lisinopril no prescription
    how to buy lisinopril without dr prescription lisinopril 5 mg side effects where to buy lisinopril without a prescription
    cost lisinopril price lisinopril brand or generic lisinopril 20mg online

  16. LanceFen表示:

    buy generic zithromax online: where can i get zithromax over the counter – generic zithromax over the counter

  17. Drugs information leaflet. Short-Term Effects.
    naltrexone effects drinking
    Actual about medication. Read information now.

  18. LanceFen表示:

    lisinopril pill: lisinopril 20 mg price without prescription – Lisin Express

  19. Michaelscoob表示:

    Clom Fast Pharm: can i purchase clomid without insurance – Clom Fast Pharm

  20. Cazraib表示:

    Приобрести диплом о высшем образовании!
    Мы можем предложить документы университетов, которые расположены на территории всей Российской Федерации. Дипломы и аттестаты выпускаются на “правильной” бумаге самого высшего качества: jobs.colwagen.co/employer/aurus-diploms

  21. BrianTom表示:

    generic amoxicillin online amoxicillin tablets in india AmOnlinePharm

  22. Danieldrymn表示:

    ZithPharmOnline: zithromax drug – buy zithromax online fast shipping

  23. Sazredg表示:

    Купить диплом о высшем образовании!
    Купить диплом университета по доступной цене возможно, обращаясь к проверенной специализированной фирме. Быстро заказать диплом: diplomgorkiy.com/ofitsialnie-diplomi-i-attestati-s-garantiej

  24. Michaelscoob表示:

    amoxicillin pills 500 mg: AmOnlinePharm – AmOnlinePharm

  25. Danieldrymn表示:

    ZithPharmOnline: zithromax 500 mg lowest price drugstore online – zithromax 500 without prescription

  26. Michaelscoob表示:

    ZithPharmOnline: order zithromax without prescription – ZithPharmOnline

  27. Richardaudit表示:

    https://clomfastpharm.com/# Clom Fast Pharm

發佈留言

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