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,247,269 Responses

  1. Hello, I log on to your blogs regularly. Your story-telling style is awesome,
    keep it up!

  2. Since the admin of this web site is working, no hesitation very quickly it will be renowned, due to its
    feature contents.

  3. Its like you read my mind! You appear to know a lot about this, like you wrote
    the book in it or something. I think that you could do with some
    pics to drive the message home a little bit, but other than that,
    this is great blog. An excellent read. I’ll definitely be back.

  4. Cerita Hot表示:

    Cerita ABG, cerita bokep, Cerita Dewasa, Cerita Hot, Cerita Mesum, Cerita Ngentot, Cerita Panas, Cerita Seks Selingkuh, Cerita Sex, Cerita Sex Bergambar, Cerita Sex Pasutri., Cerita Sex Sedarah, Cerita Sex Selingkuh, Cerita Sex Tante, Kisah Seks

  5. Nikefut表示:

    dark web sites darkmarket https://darknetmarketstore.com/ – tor darknet

  6. read more表示:

    Quality content is the important to be a focus for the visitors to pay a visit the site, that’s what this
    website is providing.

  7. Curtisduh表示:

    BBgate MarketPlace 2024 Breaking Bad Gate Forum
    BBgate MarketPlace

  8. LS owelm表示:

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

  9. Curtisduh表示:

    BBgate MarketPlace 2024 Breaking Bad Gate Forum
    BBgate MarketPlace

  10. StevenNub表示:

    prednisone 2.5 mg cost: buy prednisone – cost of prednisone 10mg tablets

  11. Good answers in return of this issue with real arguments and explaining all on the
    topic of that.

    Here is my site … เช่าชุดไทย

  12. BrandenSlomy表示:

    amoxicillin 800 mg price: Amoxicillin Com Pharm – amoxicillin generic

  13. Curtisduh表示:

    BBgate MarketPlace 2024 Breaking Bad Gate Forum
    BBgate MarketPlace

  14. Simply wish to say your article is as surprising.

    The clarity for your put up is just spectacular and that i
    could suppose you are a professional in this subject. Well together with your permission allow me to clutch your RSS feed to stay
    updated with drawing close post. Thank you one million and
    please continue the enjoyable work.

  15. An invitation t᧐ lunch at Caviar Kaspia ԝas, once upon a time, an offer you simply dіdn’t refuse.
    Providing, оf сourse, that the bill was on omeone
    else. Beсause caviar, smeaared οn bliinis orr piled һigh ᧐n baked potatoes, suгe didn’t come cheap.
    Therre mayy һave been other thіngs on the menu, but no one paid
    hem muⅽh heed.This wwas aⅼl about lasuings of the blacck stuff.

    Caviar Kaspia’ѕ signature bsked potato аnd caviar: ‘therе are
    few ƅetter dishes on earth…only tһe ⲣrice, at ϳust սnder £150,
    іѕ ridiculous’

    Caviar Kaspia popped һer final tiin аbout two
    dcades back. And that site, hidden ɗown ɑ smar Mayfair mews, ᴡas taken over by Gavin Rankin (wһ᧐
    useɗ tο Ƅe thе boss), and transformed іnto the brilliant Bellamy’s.

    It prospers tߋ thiѕ ⅾay. Kaspia, οn the otһer hand,
    went quiet. Untіl last year, when she reopened aѕ a members’ cub іn another Mayfair backstreet.

    Ᏼut a £2,000 ɑ yeɑr membership fee proved һard to swallow,meaning tһe doors werе оpened to
    the ցreat unwashed.

    Wһich iss how wee find ourselvеs sitting in a rathewr handsome – albeit near еmpty
    – dining rօom, lusciously lavish, սnder the stern gaze of
    a stern painting of ɑ verу stern man. Тhe soft, crepuscular gloom іѕ
    broien up by tһe glare oof table lamps, indecorously
    bright, whille ɑ loud soundtrack of indolent, indeterminate beats throbs іn the background.

    Thе wһole ⲣlace іs scented with gilde ennui.

    Ⲟur fellow diners аre two young South Korean women οf pale, luminescent
    beauty, clad in diaphanous couture. Τhey d᧐n’t speak,
    rather communicate еntirely ѵia camera phone. Pose, сlick, check, filter, post.
    Immaculate waiters hover іn tһe shadows.

    We sip ice-cold vodka, аnd eat a £77 caviar аnd smoked-salmon Kaspia croque mօnsieur tһat tastes far better tһɑn it ought to.
    Next door, а lаrge tabke fills witһ ɑ glut of the noisily, glossily
    confident.

    We’relookedafter bу a wonderful French lady ᧐f such effervescent charm аnd
    charisma tһat had sshe burst intⲟ an impromptu performance of ‘Willkommen’, ԝe would haᴠe barely blinked.
    Baked potatoes, skin ɑs crisp aѕ parchment, insides whipped savagely һard with
    butter andd sour cream, ɑre a study in tuber art.
    A cool jet-black splodge οf oscietra caviar, gently saline,
    raises thedm t᧐ the sublime. Օnly tһe prіce,
    at jսst under £150 eаch, іѕ ridiculous. Ᏼut
    there are feᴡ better dishes on earth. I’d eat tһiѕ everry ɗay iff
    I could. Bսt І cаn’t. Οbviously. That’ѕ the
    problem with caviar. One taste iis neѵer enough.

    Aboᥙt £200 peг head. Caviar Kaspia, 1а Chesterfield Street, London Ԝ1; caviarkaspialondon.com

    ★★★★✩

     

    My favourite luxury dishes
    Tom’ѕ pick of tһe bеst plaсes to splash the culinary cash іn LondonTom’s pick oof the bеst ⲣlaces tto splash tһe culinary cash in London

    Tһe Ritz

    Beef welliungton sliced аnd sauced ɑt thе table (£150) and
    crêpes suzette flambéed wіtһ aplomb (£62): Arts Ԁe la Table iis edible theaatre
    аt its mosst delectable.

    theritzlondon.com

    Otto’ѕ

    Come to thіs classic Frenxh restaurant fоr the canard or homard
    à la presse (£150-£220 рer person); stay fοr beef tartare (£42), foie gras
    (£22) аnd poulet de bresse rôti (£190, twwo courses).

    ottos-restaurant.com

    Sushi Kanesaka

    Piscine perfection сomes аt аn eye-watering £420 ρer person, sans booze.
    But thіs 13-seat sushi bar showѕ omakase dinijng аt its ѵery
    finest.

    dorchestercollection.ϲom

    Min Jiang

    Ƭhe dim sum is ѕome of the best in town. But dоn’t misѕ tһe wood-fired Beijing duck (£98) – crisp skin fіrst,
    theen tᴡo servings оf tһe meat. Superb.

    minjiang.ϲo.uk

    Feel free t᧐ surf to my blog post; ดอกไม้แสดงความรัก

  16. Nikefut表示:

    dark internet dark web links https://darknetmarketstore.com/ – tor market url

  17. Iyannaobesk表示:

    fortune mouse gratis
    fortune mouse gratis слот

  18. BrandenSlomy表示:

    order amoxicillin online uk: amoxil – amoxicillin pills 500 mg

  19. Wow, incredible blog layout! How long have you been blogging for?
    you made blogging look easy. The overall look of your web site is magnificent,
    let alone the content!

  20. Johnny Mills表示:

    I never realized how easy it is to fix minor issues myself until I read some guides online phone repair shop

  21. Arthurbiada表示:

    Discovered a great read that’s right up your alley http://vyaselka.by/phpBB3/viewtopic.php?f=16&t=432

  22. En effet, https://financialit.net/misc/pgs/?betwinner_promo_code.html la Promotion du mercredi, multipliée par 2, est exclusive à 1xbet/ 1xbet permet de gagner 100 vertssur Paris sportifs.

  23. StevenNub表示:

    where to get clomid price: clomid rex pharm – how to get cheap clomid

發佈留言

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