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,366,526 Responses

  1. Mostbet PL表示:

    Appreciating the time and energy you put into your site and detailed information you provide. It’s good to come across a blog every once in a while that isn’t the same outdated rehashed information. Excellent read! I’ve bookmarked your site and I’m adding your RSS feeds to my Google account.

  2. DanielAbice表示:

    https://cipharmdelivery.com/# buy cipro no rx

  3. Shantell表示:

    See What Sleeper Sectional With Chaise Tricks The Celebs
    Are Utilizing sleeper sectional with chaise – Shantell

  4. These are truly great ideas in concerning blogging.
    You have touched some nice points here. Any way
    keep up wrinting.

  5. Drug information. Generic Name.
    buying verapamil without a prescription
    Actual news about drug. Read information here.

  6. DanielAbice表示:

    http://clomidonpharm.com/# can i purchase generic clomid pill

  7. Clara Kim表示:

    I never realized how crucial an aggressive personal injury attorneys near me

  8. KennethPah表示:

    buy clomid no prescription can i get clomid price can i purchase generic clomid pill

  9. This was a wonderful post. Check out top affordable cleaning services for more

  10. DanielAbice表示:

    http://cipharmdelivery.com/# buy cipro online without prescription

  11. RobertJar表示:

    ciprofloxacin mail online: CiPharmDelivery – antibiotics cipro

  12. Hi there colleagues, its wonderful article concerning educationand completely
    defined, keep it up all the time.

  13. Предлагаем услуги профессиональных инженеров офицальной мастерской.
    Еслли вы искали ремонт стиральных машин smeg рядом, можете посмотреть на сайте: ремонт стиральных машин smeg
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  14. Austin Medina表示:

    Every detail matters when it comes to fence installation Fencing Contractor Melbourne

  15. Nikefut表示:

    darknet market dark market url tor markets links

  16. RobertJar表示:

    amoxicillin online without prescription: Amox Star – where to get amoxicillin over the counter

  17. DanielAbice表示:

    http://clomidonpharm.com/# can you get cheap clomid without rx

  18. Lily Bradley表示:

    I recently had my brake springs replaced, and it made a huge difference in my car’s performance. It’s incredible how much of an impact proper brake and suspension maintenance can have on overall safety and ride quality Suspension Services Near Me

  19. Having fun experimenting flavors not typically associated together could result unexpectedly delightful surprises when trying new combinations while cooking too Atcha | Corporate Catering London – Caterer in London

  20. This is becаuse as more bookmakers are offering live betting for football matches, punters see this being an easy
    аvеnue upon their tօ make more. How true iѕ tһis is what?

    Live betting requires a really good ɑnd sober mind. It is adviѕable
    to be focused and decisive while the match is actually in progгess.
    A faiytale ɑmong punterѕ is that it is not in order to
    understand do this on consistently if state of mind
    single.

    This can be a small error that occurs as boоkmakers attempt to strսcture the betting
    marкets in their favor. Includе also cⅼaimed that desire to limit
    the sales of their sүstem whilst not to dilute іts effect.
    Can you really trust them, or is Betting Against Alⅼ Odds just another overhуped and useless Soccer Betting sуstem?

    You are able to favour one side, leaving a joƅ opening on another side in tһe Soccer analysis goaⅼ, to encourage
    the opponent to shoot to the open next corner.
    Ԝhen the shot is taҝen, quіckly move for
    the open adveгse.

    You first set your ⲣlan gеnerate a certain quantity of wіnning
    from the bookmaker may should in ordеr to it.

    Consider it a day off whеn you have met yօur impartial.
    You should also set a limit to what we can idea. Put a stop lߋse
    part ᧐f your nett dɑily helps make the. Ӏf you hit
    the limіt, you should ѕtop and ѡait for one day thіngs a come bɑck.

    Don’t quit too soon – Although your competition may claim
    a bigger share from the market, realise that it is perseverance and endurance, consiѕtency and
    stability that ᴡill notice your team succeed for your marathon of
    economic. Some teams could be fast a season and soon faint іn the horizon once tһey
    don’t Soccer Odds realize that business is really a marathon not really 5 minute dash.
    Ⲕеep the fiɡhting philosophy. War with everything within you.
    You desire maintain fighting usually sees you through any
    obstacles or complexity.

    Favorites Odds tends to be able to ᧐n thе loᴡer side something from
    1.70-1.85. Which are serve much value particularlʏ уou are bettіng
    big considering you risk $1000 on a sіnglеs reցardless
    if you did win, you managed a $700 to $825 high profits.
    With a 3 betѕ/per day systеm which I’m adoⲣting the
    standard scenario of one win 1 draw and 1 losѕ situation wouⅼd
    result in a viguorish loss in $150-$300. The paid memberѕhips are you are
    ƅetting on undеrdogѕ the percentages tends to rangе from $1.975-$2.15 associated with scenario of merely one win 1 draw and 1
    lօss situation would гesult in minimal νiguorish loss
    or maybe often income due to your valuе possibilities.

    Thirdly, find more details about the matches, such as: opening odds,
    lineuρ of the teams, tһeir current forms, and statistіcs of
    thⲟse teamѕ. Much more information you have, calories from fat secured your bets unquestionably are.
    Believe me, yoս should do yoᥙr homework first, you need to count on luck.

    Feel free to visіt my homepaɡe :: 10 Situs judi bola terpercaya terbesar resmi di Indonesia

  21. SamuelBix表示:

    buy cipro online: CiPharmDelivery – buy cipro online canada

  22. Предлагаем услуги профессиональных инженеров офицальной мастерской.
    Еслли вы искали ремонт стиральных машин smeg цены, можете посмотреть на сайте: срочный ремонт стиральных машин smeg
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  23. DanielAbice表示:

    https://prednibest.com/# buy prednisone online fast shipping

  24. This is a different sort of opinion that many people dont usually
    talk about. Sometimes I fav stuff like this on Redit.
    Although this time Im not sure if this would be best for the
    users. Ill take a look around your site though and submit something else.

  25. SamuelBix表示:

    generic clomid price: clomidonpharm – can you get cheap clomid without a prescription

  26. Попробуйте любимую sushi holl от sushi-holl! Мы предлагаем многочисленные комбинации: с цыплёнком, свининой, даровами моря и овощными добавками. А необычные соусы усиливают каждому блюду яркость вкуса. WOK – это идеальное решение для тех, кто любит питательные и аппетитные блюда. Заказ можно сделать онлайн, и уже в ближайшее время ароматное блюдо будет у вас на столе. Не забудьте заказать известной азиатской кухней, прямо дома.

發佈留言

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