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,273,485 Responses

  1. discover here表示:

    This post will assist the internet users for building up new weblog or even a blog from start
    to end.

  2. выведение из запоя воронеж стационар http://www.masa.forum24.ru/?1-16-0-00002629-000-0-0-1730749828 .

  3. HenrydeT表示:

    vavada казино вавада казино вавада

  4. Jamesdiure表示:

    пин ап вход: pinup kazi – пин ап казино официальный сайт

  5. Way cool! Some extremely valid points! I appreciate you
    writing this post plus the rest of the site is also very good.

  6. look at here表示:

    When someone writes an post he/she keeps the
    plan of a user in his/her brain that how a user can be aware of
    it. So that’s why this article is amazing.

    Thanks!

  7. DarioTob表示:

    вавада: вавада – вавада казино онлайн

  8. Learn More表示:

    I’m not that much of a internet reader to be honest but your blogs really nice, keep it up!
    I’ll go ahead and bookmark your site to come back in the future.
    Cheers

  9. Josephmax表示:

    http://pinup-kazi.kz/# пин ап кз

  10. DarioTob表示:

    vavada-kazi.ru: казино вавада – казино вавада

  11. This design is incredible! You most certainly know how to keep a reader amused.
    Between your wit and your videos, I was almost
    moved to start my own blog (well, almost…HaHa!) Fantastic job.
    I really enjoyed what you had to say, and more than that,
    how you presented it. Too cool!

  12. How To Explain Men Masterbator To Your Grandparents Best Male Masturbators

  13. DarioTob表示:

    казино вавада: казино вавада – вавада казино онлайн

  14. Penipu表示:

    I’m amazed, I have to admit. Seldom do I encounter a blog that’s
    both educative and entertaining, and without a doubt, you have hit the nail on the head.
    The issue is something that too few folks are speaking intelligently about.
    I am very happy that I came across this in my hunt for something concerning this.

  15. Wonderful blog! Do you have any suggestions for
    aspiring writers? I’m planning to start my own blog soon but I’m a little lost on everything.
    Would you propose starting with a free platform like WordPress or go for a paid option? There are so many
    choices out there that I’m completely confused .. Any ideas?
    Kudos!

  16. If some one needs expert view about blogging
    after that i propose him/her to visit this weblog, Keep up the pleasant job.

    Here is my web site :: realtor in Meridian Ms

  17. Gregoryprobe表示:

    Цифровые технологии в нынешнее время проникают во все сферы жизни, виртуальный номер проявляет себя как неотъемлемым инструментом для эффективного и безопасного общения https://kem-live.ru/interesnoe/view/virtualnyj-nomer-i-ego-ispolzovanie

  18. DarioTob表示:

    vavada-kazi.ru: vavada – вавада онлайн казино

  19. HenrydeT表示:

    пин ап кз pinup-kazi.kz пин ап кз

  20. Nikefut表示:

    darkweb marketplace blackweb dark websites

  21. buket_udma表示:

    Идеальный букет невесты для вашей свадьбы, которые вас вдохновят.
    Шаг за шагом: соберите уникальный букет невесты, который станет вашим сокровищем.
    Как выбрать букет невесты, который подчеркнет ваш стиль, для свадебной церемонии.
    Бюджетный вариант букета невесты: красиво и доступно, который порадует вас и вашего жениха.
    Свежие цветы или нет: какой букет невесты лучше, для сохранения воспоминаний о свадьбе.
    Букет невесты в стиле минимализм, для свадьбы в скандинавском стиле.
    Секреты подбора букета невесты к платью, для выразительных свадебных образов.
    заказать букет невесты нижний новгород заказать букет невесты нижний новгород .

  22. Mary Woods表示:

    When purchasing auto insurance coverage in Pasadena TX, bear in mind the protection restrictions. The greatest auto insurance policy in Pasadena TX ought to supply the right equilibrium of coverage at an inexpensive price auto car insurance

  23. DarioTob表示:

    pinup kazi: пин ап зеркало – пин ап зеркало

  24. HenrydeT表示:

    пин ап казино онлайн pinup-kazi.kz pin up казино

  25. Hey I know this is off topic but I was wondering if you knew of any widgets I could add to
    my blog that automatically tweet my newest twitter updates.
    I’ve been looking for a plug-in like this for quite some time and was
    hoping maybe you would have some experience with something like this.
    Please let me know if you run into anything.
    I truly enjoy reading your blog and I look forward to your new updates.

  26. Drugs prescribing information. Effects of Drug Abuse.
    how to buy generic motrin without insurance
    Some trends of pills. Read here.

  27. Dztrader.com表示:

    Adult Entertainment 오피사이트 (Dztrader.com)

發佈留言

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