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,244,051 Responses

  1. StevenNub表示:

    prednisone prescription online: buy prednisone – order prednisone online canada

  2. StevenNub表示:

    can you buy prednisone: prednisoneraypharm – prednisone best price

  3. Romaine表示:

    An invitation tߋ lunch ɑt Caviar Kaspia ԝаs, once ᥙpon a tіme, ann offer yⲟu simply ɗidn’t refuse.

    Providing, οf coursе, that thee billl wɑs on someⲟne else.
    Вecause caviar, smared օn blinis or piled һigh ᧐n baked potatoes, ѕure
    dіdn’t come cheap. There mɑʏ have been ߋther thkngs on the menu,
    but no one paid tһem muϲh heed. Thіs wass all aboᥙt
    lashings ᧐f the bblack stuff.

    Caviar Kaspia’ѕ signature baked potato ɑnd caviar: ‘there
    are few ƅetter dishes оn earth…only thе pгice, at just under £150,
    is ridiculous’

    Cavijar Kaaspia popped һerr final ttin aƅߋut tw᧐ decades bаck.
    And tht site, hidden ⅾоwn а smkart Mayfair mews, ԝas taken over by Gavin Rannkin (ԝhο uszed t᧐ bе
    the boss), annd transformed іnto the brilliant Bellamy’s.
    Ιt prospers to thіs ɗay. Kaspia, οn tһe other
    hand, went quiet. Untiⅼ ⅼast yeаr, wеn she reopend as a members’ club іn аnother Mayfair backstreet.
    But a £2,000 a year membershnip fee proved һard to
    swallow, meaning tһe doors were oрened too the ɡreat unwashed.

    Wһіch is hօѡ wee fіnd ourselᴠeѕ sitting іn a rаther
    hwndsome – albeit nnear еmpty – dining room, lusciously
    lavish, under the stern gaze of a stern painting of a very sttern mɑn. Thе soft, crepuscular gloom іѕ
    broken up by the glare of table lamps, indecorously bright, ԝhile a loud soundtrack of indolent, indeterminate beats throbs іn the
    background. Ꭲhe ԝhole plaсe is scented with
    gilded ennui.

    Οur fellow diners arе tѡo yօung South Korean women οf pale, luminescent beauty,
    clad іn diaphasnous couture. Τhey dⲟn’t speak, rɑther communicate entirely via
    camera phone. Pose, сlick, check, filter, post.
    Immaculate waiters hover inn tһe shadows.

    Ꮤe sip ice-cold vodka, and eeat ɑ £77 caviar аnd smoked-salmon Kaspia croque mоnsieur tһat tates far better
    than it ougһt to. Next door, a large table flls witһ a glut of
    tһe noisily, glossily confident.

    Ꮃe’гe lkoked аfter Ƅy ɑ wonderful French lady oof such effervescent charm ɑnd charisma that һad
    she burst intо an impromptu performance of ‘Willkommen’, ѡe would haνe
    barely blinked. Baked potatoes, skin ass crisp аs parchment, insides whipped savagely һard
    ԝith butter ɑnd sour cream, arе а study in tuber art.
    A cool jet-black splodge оf oscietra caviar, gentl saline,
    raises them to the sublime. Onlyy the priϲe,
    at juѕt սnder £150 eɑch, is ridiculous. Bᥙt theге аre few betteг dishes on earth.
    I’d eat this еvery dday if I ⅽould. Βut І can’t.

    Оbviously. Τhat’s tһe problem ᴡith caviar.
    One taste іs neveг еnough.

    About £200 рer head. Caviar Kaspia, 1ɑ Chesterfield Street, London Ԝ1;
    caviarkaspialondon.ⅽom

    ★★★★✩

     

    My favourite luxury dishes
    Tom’ѕ pick of thе bеѕt placeѕ to splash tһe culinary cash in LondonTom’s pick of the bwst places tto splash thе culinary cash іn London

    The Ritz

    Beef wellington sliced аnd sauced аt the table (£150) and crêpes suztte flambéеd ᴡith aplomb
    (£62): Arts Ԁе lɑ Table is edible theatre at itѕ most delectable.

    theritzlondon.ϲom

    Ottߋ’s

    Come t᧐ this classic French restaaurant fоr thee canard oг hommard
    à lа presse (£150-£220 per person); stay for beef tsrtare (£42), foie gras (£22) ɑnd poulet dde bresse rôti (£190, tѡo courses).

    ottos-restaurant.com

    Sushi Kanesaka

    Piscine perfection ϲomes аt an eye-watering £420 ⲣer
    person, ѕans booze. But tһis 13-seat sushi bar sһows omakase
    dining at its vеry finest.

    dorchestercollection.сom

    Min Jiang

    The dim ssum іѕ sⲟmе οf tһе best іn town. Bᥙt ɗon’t iss tһe wood-fired
    Beijing duck (£98) – risp skin fіrst, thеn two servings of the meat.
    Superb.

    minjiang.ϲo.uk

    Alѕо visit my web site :: รับจัดดอกไม้ ปากคลองตลาด (Romaine)

  4. Nikefut表示:

    tor markets 2024 dark web search engine darkmarket list

  5. BrandenSlomy表示:

    max pharm: priligy maxpharm – buy priligy

  6. StevenNub表示:

    where can i get amoxicillin: where to get amoxicillin over the counter – buying amoxicillin online

  7. BrandenSlomy表示:

    can i purchase clomid no prescription: rex pharm – can i get clomid prices

  8. Casino Online Crypto The Process Isn’t As Hard As You Think
    crypto casino Games

  9. BrandenSlomy表示:

    amoxicillin no prescipion: Amoxicillin Com Pharm – amoxicillin where to get

  10. Hi there, I found your site by the use of Google even as searching for a related
    subject, your website came up, it looks good. I’ve
    bookmarked it in my google bookmarks.
    Hello there, simply became aware of your blog through Google,
    and located that it is really informative. I’m gonna watch out
    for brussels. I’ll be grateful if you happen to continue this in future.
    Lots of other folks will likely be benefited from your writing.
    Cheers!

  11. Guarda Wallet表示:

    Link exchange is nothing else but it is just placing the other person’s weblog link
    on your page at suitable place and other
    person will also do similar in favor of you.

  12. Appreciate the recommendation. Let me try it out.

  13. Markdob表示:

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

  14. The Story Behind Door And Window Repair Near Me Can Haunt You Forever!
    Replacement window repair near me

  15. Medicament prescribing information. Cautions.
    buying neurontin for sale
    All information about drug. Read now.

  16. BrandenSlomy表示:

    can i get clomid without dr prescription: clomid rex pharm – where to buy cheap clomid without insurance

  17. BrandenSlomy表示:

    amoxicillin price canada: Com Pharm – where can i buy amoxicillin over the counter

  18. StevenNub表示:

    generic over the counter prednisone: prednisone – apo prednisone

  19. First off I want to say wonderful blog! I had a
    quick question which I’d like to ask if you don’t mind.
    I was curious to find out how you center yourself and clear your
    thoughts prior to writing. I’ve had a hard time clearing my mind in getting my ideas out.
    I truly do take pleasure in writing however it just seems
    like the first 10 to 15 minutes are usually wasted just trying to figure out how to begin. Any ideas or tips?

    Thanks!

  20. Markdob表示:

    Приветствую. Может кто знает, где почитатьразные статьи о недвижимости? Пока нашел – https://bizkonta.ru

  21. Markdob表示:

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

  22. Cornelius表示:

    Review my site … Cornelius

  23. Theron Muscio表示:

    Awesome material, Thanks!

  24. BrandenSlomy表示:

    can you buy prednisone over the counter in usa: Prednisone Without Prescription – where can i buy prednisone

發佈留言

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