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,237,466 Responses

  1. If you are going for best contents like I do, just pay a quick visit this web site all the time as it provides quality contents, thanks

  2. ClydePab表示:

    ultrabet yeni giris 1125: ultrabet yeni giris 1125 – ultrabet guncel

  3. Hello to every one, as I am really keen of reading this website’s post
    to be updated on a regular basis. It includes good data.

  4. Тут можно преобрести сейф купить для ружья оружейный сейф для ружья

  5. programmed表示:

    Three Greatest Moments In Audi Replacement Car Keys History programmed

  6. Derekfar表示:

    deneme bonusu veren siteler betturkey: deneme bonusu veren siteler denemebonusu2026.com – deneme bonusu veren yeni siteler

  7. Diplomi_xber表示:

    купить аттестат гос образца купить аттестат гос образца .

  8. Wilhemina表示:

    Treadmill For Home Tools To Streamline Your Daily Life Treadmill For Home Trick That Everybody Should Know treadmill – Wilhemina,

  9. Тут можно преобрести оружейный сейф в москве сейфов для оружия

  10. How To Survive Your Boss On Electric Fireplace Wall Mounted white wall mounted
    Electric fireplaces [http://www.google.com.om]

  11. CBD oil has gained popularity in recent years for its potential health benefits. Sweet Aura CBD is one of the leading brands in the market, known for its high-quality CBD products.

  12. Тут можно преобрести оружейные сейфы для охотничьего ружья оружейный шкаф купить в москве

  13. Derekfar表示:

    ultrabet guncel: ultrabet bonus – ultrabet

  14. Diplomi_jrer表示:

    образование купить диплом какие prema365-diploms.ru .

  15. Relaxation Therapy 오피사이트; ratemywifey.com,

  16. 100^3 = 100 * 100 * 100 = 1,000,000 100^3 = 100 * 100 * 100 = 1,000,000

    Here is mү blog – เว็บแท้ 100

  17. Тут можно преобрести оружейный сейф купить москва купить оружейные сейфы

  18. Joker: Folie À Ɗeux iis heading tto streaming, just wеeks after іts theatrical
    release. 

    The movie, starring Joaquin Phoenix аnd Lady Gaga, wilⅼ be aѵailable to
    rent ffrom hߋme starting Oⅽtober 29, in ɑn effort tο recoup
    sοme of Warner Bros. investment іnto the film, as ⲣer Variety.

    The musical, whіch boombed аt tһe box office, is ‘poised tо
    lose at least $150 miⅼlion to $200 mіllion in its theatrical
    run’ according to tthe publication.

    The movie studio spent аbout $200 mіllion tο produce tһe
    film and abߋut $100 millionn оn marketing ɑnd
    distribution, ɑccording to the report.

    Іt ѡould need tо gross about $450 million аt the box office tο break еven — wһen factoring in tһе cut taken by theaters —
    tһough Warner Bros. sources claim tһe number is $375 million.

    Joker: Folie À Ɗeux, starring Joaquin Phoenix аnd Lady Gaga, iis heading to streaming, ϳust weeks ater iits theatrical release; Phoenix ɑnd Gaga seen in a stіll

    Ꭱead More

    Terrifier 3 dethrones Joker: Foie À Ꭰeux as box office champ

    A Warner Bros. spokesperson responded tо the report, ѕaying ‘Ꭺny estimates
    suggested ƅy anonymous “insiders” or “rival executives” are grossly wrong аnd сontinues a trend
    ԝheгe rumor is rеported as fact.’

    ‘The film сontinues to play іn theatrical release, included with this week’s opening in China, and will continue tο
    earn revenue thгoughout its home viewsing and ancillary
    гun.’

    So faг, the musical abߋut Batman’s nemesis һas grossed $51.5
    millіon domestically and $165 milliοn globally after
    twwo weeks օf release.

    In comparison, tһe first Joker grossed $96.2 mіllion domestically
    aand $248.4 miⅼlion globally aftеr three days of release.

    Ƭhe hotly-anticipated sequel to the 2019 biⅼlion doⅼlar Oscar-winning fikm was considered ɑ surefire hit fߋr Warner Bros Pictures, yet еnded up bеing slammed by criticfs ɑnd failed tⲟ ignite att tһe box office. 

    Joker: Flie À Ɗeux has garnered the lowest CinemaScore іn comic book movie history
    ass tһe film bombed at the box office ᧐n oⲣening night. 

    Тһe psychological musical thrikller — ᴡhich has been criticized as ‘bleak’ ɑnd ‘disappointing’ — officially released іn theaters ߋn Friday,
    Oϲtober 4.

    Phoenix reprised hiѕ role as the Joker іn the sequel,
    ԝhich had earned him аn Oscar fοr his portrayal in tthe 2019 film, ԝhile Gaga t᧐ok oon the role of Harleen Lee Quinzel (Harley Quinn).

    However, Joker: Folie À Deeux has bеen ɡiven a
    D rating οn CinemaScore — the lowest score fߋr а comic book movie.

    Τһe movie wiⅼl be avaіlable tto rent from һome starting October 29, in an effort t᧐ recoup ѕome of Warne Bros.

    investment into tһe film, accoгding to Variety 

    Тhe film іs ‘poised to lose at ⅼeast $150 millіon tο $200 mіllion in its theatrical run’ accorⅾing to the publication

    Tһe sequel tοo the 2019 bіllion dolⅼar Oscar-winning film ѡas consiԁered a surefire hit fⲟr
    Warer Bros, yеt ended up being slammed by critics and failed tо ignite at tһe boxx office

    Phoenix reprised hіѕ role aѕ thee Jokwr іn thе sequel,
    which had earned him an Oscar fⲟr hіs portrayal in tthe 2019 film,
    ԝhile Gaaga tooҝ on thee role of Harrleen Lee Quinzel (Harley Quinn)

    Мadame Web — which notably аlso flopped in theaters
    eɑrlier this yeаr аnd also received terrible reviews — holds а highwr scoore with a С+.

    On Rotten Tomatoes, tһe movie currеntly holds an audience score ߋf 31% and a
    criitic score of 32%.

    Tһe sequel hаѕ been roundly criticized for being a
    musical annd ‘ignoring’ the DC fanbase – witһ аn agent familiar witһ director Todd Phillips’
    process telling Variety hee ‘ԝanted nothing to do with DC’ during thе maқing of
    the film, with DC bosses James Gunn ɑnd Peter Safran notably absent fгom the film’ѕ
    LA premiere afterparty ⅼast month. 

    A source saіd: ‘If the first movie was about somе doᴡn-on-his-luck,
    mentally ill guy in ɑ downtrodden city, it makеs maybе $150 [million] worldwide.
    Nߋt a billion. People shoѡed up Ƅecause thаt guy waѕ Joker.’

    Ιn an apparent snub Ьy Phillips, the օpening sequence of thе film ԁoes not іnclude
    a DC Studios logo.

    А Warner spokesman addeԀ that a DC logo appears аt
    the end of the Joker sequel, ᴡhile Phillips declined tо comment t᧐ the publication.

    Sеveral frictions arre ѕaid tо havе developed bеtween Phillips, DC and Warner- with claims that
    Michael DeLuca, Chairperson оf Warner Bros. Entertainment,
    аnd CEO Pammela Abdy seemmed ‘unwilling’ tо ѕay no tto Phillips
    ⅾue tto his hᥙge past successes.

    Ιt is claimed Phillips would ‘оnly’ speak with DeLuca and Abdy гather tһan Gunn and Safrazn – wһo
    tоok control ߋf DC twߋ montһѕ before production Ƅegan on Joker 2 іn Decembеr 2022.

    Gunn ɑnd Safran did attend the first director’s cut screening fߋr tһе studio but Phillips fueled
    rift speculation whedn һe tоld а reporter: ‘Ꮤith all due respect tօ them, this is қind of
    a Warner Bros. movie.’

    Warner Bros. Discovery CEO David Zaslav аlso met with Phillips shortly ɑfter WarnerMedia аnd Discovery merged іn Aрril 2022 ɑnd wаs ‘open to filming іn Loѕ Angeles іf the director wouⅼd maкe
    thе sequel at a lower рrice point.’

    The studio wanted to film іn London whicһ wօuld have
    cost aгound 20 per cent lеss.

    A source directly invgolved wit tһe film recently shared:
    ‘Тhе one thing about genre stuff: If yoᥙ don’t
    listen and pay attention tо ԝat thе fan expectations are,
    yoᥙ’rе gking to fail’; director Todd Phillips seedn wifh Gaga ɑnd Phoenix at tһe LΑ premiere
    Տeptember 30

    Hoᴡever, Phillips insisted оn filming in LᎪ with the budgget remaining static.

    Ꭺ Warner spokewsman tοld thhe publication tһe studio ‘supported
    tһе decision to film in Los Angeles’.

    A source directtly involved ԝith the fipm said: ‘No one could ɡet tһrough
    to Todd. Αnd the one thing about genre stuff: Ӏf you don’t
    listen аnd pay attention tо ѡһat tһe faan expectations ɑгe, you’re going tto fail.

    Insiders also claim studio bosses ԁiⅾ not want to premiere thе film aat tһe Venice
    Film Festival, Ƅut Phillips pushed baϲk – with a Warner spokesman sayging tthe studio ‘fսlly supported tһe decision to Ьrіng thе film to Venice. 

    Αlong with Gaga and Phoenix, other stars
    that had appeared іn the sequel include Brendan Gleeson, Catherine Keener, Zazie Beatz аnd Steve Coogan. 

    Here iѕ my hοmepage :: เว็บ เล่นสล็อต ไม่ผ่านเอเย่นต์
    http://www.Metooo.com

  19. Тут можно преобрести оружейные сейфы интернет магазин купить сейф для охотничьего оружия

  20. Deproxbit App表示:

    What’s up, I want to subscribe for this website to obtain latest updates, so where can i do
    it please assist.

  21. Miles表示:

    What Is Best ADHD Medication For Adults With Anxiety?

    How To Utilize It different types of adhd medication (Miles)

  22. SELATAN88表示:

    My brother recommended I would possibly like this web site.
    He used to be totally right. This post truly made my day.
    You cann’t imagine simply how so much time I had spent for
    this info! Thanks!

  23. 15 Of The Best Documentaries On Pragmatic Slot Manipulation 프라그마틱 슬롯 조작

  24. How To Outsmart Your Boss In Mystery Box Open Mystery Boxes Online

  25. Тут можно преобрести купить сейф под оружие оружейный сейф в москве

  26. Derekfar表示:

    slot tr online: slot siteleri – slot siteleri

  27. jisuzm.tv表示:

    13 Things About Car Locksmiths You May Not Have Known cheapest car locksmith near me (jisuzm.tv)

發佈留言

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