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,726 Responses

  1. Dereketerm表示:

    prednisone 2 mg daily: prednisone canada prescription – can i buy prednisone from canada without a script

  2. Temanbfhk表示:

    Для тех, кто хочет начать с выгодой, доступен Мелбет промокод, который позволяет получить бонусы на первый депозит. Используйте этот код для успешного старта на платформе.

  3. Dereketerm表示:

    priligy maxpharm: dapoxetine price – cheap priligy

  4. Uazrdzb表示:

    Приобретение диплома ПТУ с сокращенной программой обучения в Москве
    manikyur-zheleznogorsk.ru/kandidat-nauk-kupit-diplom-v-reestre.html

  5. Узнай все о степени варикоцеле варикоцеле 3 степени

  6. Тут можно преобрести оружейные сейфы и шкафы для охотничьего шкаф для оружия

  7. The One Car Accidents Lawyer Near Me Trick Every Person Should Know
    Car Accidents Attorneys

  8. Medicament information for patients. Drug Class.
    how to buy fosamax price
    Best about drugs. Read information here.

  9. Hello just wanted to give you a quick heads up. The words in your content seem to be running off the screen in Opera.

    I’m not sure if this is a format issue or something to do with browser compatibility but I thought I’d post to let you know.
    The style and design look great though! Hope
    you get the problem solved soon. Cheers

  10. Тут можно преобрести купить оружейный сейф цена оружейные сейфы для охотничьего ружья

  11. Hi! I know this is kinda off topic however , I’d figured I’d ask.
    Would you be interested in exchanging links or maybe guest writing a blog article or vice-versa?

    My site covers a lot of the same subjects as yours and I believe we could greatly
    benefit from each other. If you happen to be interested feel free to shoot me an e-mail.
    I look forward to hearing from you! Terrific blog by the way!

  12. I visited several web sites but the audio feature for audio songs current at this website is
    genuinely superb.

  13. Nikefut表示:

    dark web link dark web market list blackweb official website

  14. Bradleygoath表示:

    prednisone 20mg nz prednisone ray pharm prednisone 54899

  15. BrandenSlomy表示:

    max pharm: Priligy tablets – max pharm

  16. Bradleygoath表示:

    amoxicillin 875 mg tablet amoxil amoxicillin 500mg prescription

  17. SajiToto表示:

    Thanks a lot fоr sharing thiѕ ᴡith all of uѕ you actually understand ᴡhat yоu
    агe talking aⲣproximately! Bookmarked. Kindly ɑlso consult with my site =).
    We may have a link exchange arrangement Ƅetween us

    Aⅼso visit my blog post: SajiToto

  18. StevenNub表示:

    average cost of prednisone: Prednisone Without Prescription – how can i order prednisone

  19. I’m truly enjoying the design and layout of your website.
    It’s a very easy on the eyes which makes it much more pleasant
    for me to come here and visit more often. Did you hire out a designer to create your theme?
    Exceptional work!

  20. BrandenSlomy表示:

    dapoxetine online: priligy maxpharm – priligy

  21. Blakesmema表示:

    shth.ru/ — Полный спектр услуг по созданию кухонь.

發佈留言

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