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,169,482 Responses

  1. 11 “Faux Pas” You’re Actually Able To Do With Your Upvc
    Windows Repair upvc window Repair

  2. aladin138表示:

    I was recommended this blog by means of my cousin. I’m no longer sure whether this post is written by him as no one else know such distinct
    about my problem. You are wonderful! Thanks!

  3. dob表示:

    Всем привет! Подскажите, где почитать разные блоги о недвижимости? Сейчас читаю https://an72.ru

  4. Good replies in return of this query with solid
    arguments and describing everything about that.

  5. Asbestos is a mineral that occurs naturally that
    was once extensively used in manufacturing and construction industries.

    Anyone who was exposed to Asbestos Litigation often suffered from serious and life-threatening diseases.

  6. baskili poset表示:

    Hey there just wanted to give you a quick heads up. The words in your post seem to
    be running off the screen in Opera. I’m not sure if this
    is a format issue or something to do with internet browser compatibility but I figured I’d post to let
    you know. The layout look great though! Hope you get
    the issue fixed soon. Thanks

  7. Leibniz International Conference on https://water-coin.wtf/ Informatics (lipics). Yang, Yingzhi (May 18, 2018). “There is a bitcoin bubble,” says alibaba executive chairman Jack Ma.”

  8. Gopek178表示:

    І’m curious to find оut what blog platform you hаѵe bеen uѕing?
    I’m experiencing some smaⅼl security issues witһ my ⅼatest site and
    I would like to find sօmething mοгe secure.
    Ɗo yߋu haᴠe any suggestions?

    My homepage; Gopek178

  9. Kay表示:

    15 Hot Trends Coming Soon About 1kg Coffee Beans 1kg of coffee
    beans [Kay]

  10. Fela claims表示:

    10 Life Lessons We Can Learn From Federal Employers Fela claims

  11. І am regular visitor, how are you еvеrybody? This post posted at this web page is actuаlly nice.

    Also visit my web Ьlog DedicatedProxies.net

  12. Introduction To The Intermediate Guide For
    Coffee Machine Nespresso coffee machine cheap

  13. JoshuaDup表示:

    Edson Arantes do Nascimento https://pele.prostoprosport-br.com Brazilian footballer, forward (attacking midfielder. Played for Santos clubs) and New York Cosmos. Played 92 matches and scored 77 goals for the Brazilian national team.

  14. AndreJZ表示:

    Ведущий праздников – это человек, который ответственен за организацию и проведение праздничных мероприятий, таких как корпоративные вечера, частные праздники, свадьбы, дни рождения и т.д. Ведущий праздников обычно является лицом, которое обеспечивает развлекательную программу, общается с гостями, контролирует ход мероприятия и создает праздничную атмосферу.

    Обычно, ведущий праздниковantwort за следующиеaspectы праздника:

    1. Разработка сценария мероприятия и координация его выполнения.
    2. Развлекательная программа: выбор артистов, музыки, игр и других мероприятий.
    3. Организация и проведение конкурсов, игр и других конкурсных мероприятий.
    4. Управление временем и расписанием мероприятия.
    5. Общение с гостями, отвечая на их вопросы и обеспечивая их комфорт.
    6. Координация с техническим персоналом,such as sound engineers, lighting technicians, and other event staff.
    7. Решение нештатных ситуаций и кризисных ситуаций, которые могут возникнуть в ходе мероприятия.

    Ведущий праздников harus быть харизматичным, иметь грамотную речь и навыки общения, бытьorganizovanny и уметь работать под давлением времени.
    заказть можно организатора у нас Ведущий на Новый Год

    время работы с 8.00 до 19.00 званите будем рады вам помочь

    123

  15. Please let me know if you’re looking for a article author for your weblog.

    You have some really great posts and I feel I would be a good asset.
    If you ever want to take some of the load off, I’d love to write some content for your blog
    in exchange for a link back to mine. Please send me an email
    if interested. Kudos!

  16. It’s amazing to pay a visit this web page and reading the views of all friends concerning this
    post, while I am also eager of getting know-how.

  17. SGS786表示:

    Thanks for sharing your info. I truly appreciate your
    efforts and I am waiting for your next write ups thanks once
    again.

  18. 10 Meetups Around Best Home Coffee Machine You Should Attend Best Coffee machine under £100

  19. Write more, thats all I have to say. Literally, it
    seems as though you relied on the video to make your point.
    You definitely know what youre talking about, why waste your intelligence on just posting videos to
    your site when you could be giving us something informative to read?

  20. A mesothelioma lawyer may help victims receive compensation.
    These firms have deep industry resources and proprietary asbestos databases that they utilize to link a mesothelioma-related diagnosis with exposures to Asbestos Attorney from the past.

  21. Coffee表示:

    Hi, i believe that i saw you visited my blog thus i
    came to return the desire?.I am trying to to find issues to enhance my website!I guess its
    good enough to use a few of your concepts!!

  22. Howdy! Quick question that’s entirely off topic.
    Do you know how to make your site mobile friendly?

    My site looks weird when browsing from my iphone 4.
    I’m trying to find a template or plugin that might be able to correct this problem.

    If you have any recommendations, please share. Thanks!

  23. dob表示:

    Всем привет! Подскажите, где найти полезные блоги о недвижимости? Пока нашел https://an72.ru

  24. facebook sex表示:

    Look into my web-site – facebook sex

發佈留言

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