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,198,300 Responses

  1. 913875.xyz表示:

    Wood Stoves: What’s The Only Thing Nobody Is Talking About 913875.xyz

  2. My partner and I stumbled over here by a different page and thought I might
    check things out. I like what I see so now i am following you.
    Look forward to finding out about your web page repeatedly.

    my blog post Lottery Defeater Software

  3. betflik 8k表示:

    Thank you for the good writeup. It in fact was
    a amusement account it. Look advanced to more added agreeable from you!
    However, how could we communicate?

  4. porn xnxx表示:

    I know this web site gives quality dependent content and additional data, is there
    any other web page which provides these kinds of stuff in quality?

  5. Hey there! Do you use Twitter? I’d like to follow you if that would be ok.
    I’m definitely enjoying your blog and look forward to
    new posts.

  6. You’ll Be Unable To Guess Railroad Injuries Lawyers’s Benefits railroad injuries Lawyer

  7. Double Glazing Companies Near Me Tools To Improve Your Daily Life
    Double Glazing Companies Near Me Trick That Every Person Must Learn double glazing companies near Me

  8. BomesJoype表示:

    Lorem Ipsum has been the industry’s standard dummy text https://coffeedrama.in/xzmprf of type and scrambled it to make a type specimen book.

  9. Приветствую. Подскажите, где найти разные статьи о недвижимости? Пока нашел https://vortex-los.ru

  10. Where Are You Going To Find Double Glazing Deals Near Me Be One Year From Now?
    double Glazing Window handles

  11. The Most Hilarious Complaints We’ve Received About Car Boot Mobility
    Scooter https://www.arlennizo.top/

  12. The Best Free Keyword Tools Round The Web 백링크 만들기

  13. 15 Double Glazing Installers Near Me Benefits That Everyone Should Be Able To Cheap Double glazed windows

  14. Pills information. Short-Term Effects.
    how can i get generic anastrozole without insurance
    Best trends of medicine. Get here.

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

  16. StephenNef表示:

    внж в испании без права на работу https://vnzh24.ru/

  17. porn xnxx表示:

    Your style is so unique compared to other folks I have read stuff from.
    Thanks for posting when you have the opportunity, Guess I’ll just bookmark
    this page.

  18. Why Nobody Cares About Double Glazed Window Near Me Double Glazed Windows Replacement

  19. Pretty section of content. I simply stumbled upon your weblog and in accession capital to claim that
    I get actually loved account your weblog posts.

    Anyway I’ll be subscribing for your augment or even I achievement you get right of entry to constantly quickly. http://Bemathematical.com/__media__/js/netsoltrademark.php?d=fishtanklive.wiki%2FUser%3AGloryNiles1608

  20. 中国美女表示:

    Hey there! I’ve been following your web site for some time now and finally got the courage to go ahead and give you a shout out from
    Houston Texas! Just wanted to mention keep up the excellent job!

    Also visit my blog post – 中国美女

  21. Lunrlqu表示:

    Привет, друзья!
    Мы изготавливаем дипломы любой профессии по приятным тарифам.
    Мы предлагаем документы ВУЗов, расположенных в любом регионе РФ. Можно купить диплом за любой год, включая сюда документы старого образца СССР. Дипломы и аттестаты выпускаются на бумаге высшего качества. Это дает возможности делать настоящие дипломы, которые не отличить от оригинала. Они заверяются необходимыми печатями и подписями.
    Гарантируем, что при проверке документа работодателем, подозрений не возникнет.
    Где заказать диплом по нужной специальности?
    teplichnaya.ru/viewtopic.php?f=18&t=503027

  22. Drugs information for patients. Brand names.
    cost of pioglitazone tablets
    Actual trends of medicine. Read information here.

  23. I blog often and I genuinely appreciate your content. Your article
    has truly peaked my interest. I am going to take a note of your site and keep checking for new information about once per week.

    I opted in for your Feed too.

  24. Build Credit From Scratch – 5 Ways To Determine A Solid Credit History
    대출 이자 계산기

  25. All Bets On Yellow: Double Spins Bonus Roulette 프라그마틱 슬롯

  26. See What Double Glazing Repair Near Me Tricks The Celebs Are Utilizing double Glazing repair (mylivingplan.Com)

  27. Guide To Replacement Upvc Window Handles: The Intermediate Guide For
    Replacement Upvc Window Handles Replacement Upvc Window handles

  28. Drugs information leaflet. Cautions.
    can i buy divalproex prices
    Some information about drug. Read now.

發佈留言

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