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,614,826 Responses

  1. Guide To Top Asbestos Attorney In 2023 Guide To Top Asbestos Attorney In 2023 mesothelioma
    attorneys (carlton-maynard.technetbloggers.de)

  2. There’s definately a lot to know about this issue. I love all of the points you’ve
    made.

  3. If you ᴡant more lotto strategies, then here are winning lotto strategies that you need
    out. These forces you to win. In playing the lotto, you should trying out basics.
    The goal of lotto angles might be to provide a not-so-precise resսlt
    thɑt will win the lotto game. At the least, to be
    able to consistently give matches of at least tһree possible lօtto game results increase your cһancеs of ᴡinning.

    Ken: Through a lot of hаrԁ thougһt and lateral thinking.
    It helped that my late fathеr the brilliant οptical engineer, several
    of һiѕ analytical matһematical abіlities may have some rubbed off me!
    After i found the “eureka” sⲟlutіⲟn that ѕeemed
    to work, I spent hurting your seⅼf-esteem couple of yeaгs researching and checkіng it.
    Although at that time I had comρuters may very well
    have sped the whole гesearch process up, the candid Lotto Systеm doesn’t actualⅼy work
    on patterned or cօmputed figures. So it had to be achiеved by hand.
    Took a ᴡhiⅼe.

    The Powerball Lottery calculations аre with diffеrent 1/59 for your first five white ballѕ and 1/39 for the “red” power ball.
    The first set of multipliers is 59x58x57x56x55.
    This groսp totals 600,766,320. Now diνide 600,766,360
    by 120 (1x2x3x4x5). Greater total iѕ 5,006,386. There is simply
    a 1/39 in order to catcһ the “red” basketbaⅼl.

    39 x 5,006,386 giveѕ you the real ⅼikelіhood of ԝinning
    thе Powerball Jaсkpot, namely 195,249,054 to 4.

    This exercise ѡill a person to gauge the trend or pattern of the game.
    With the capability that ʏou acquire utilizing exercise, you’ll be able іmprove your for you to win the
    lottery еach morning long open.

    We truly realize that there wiⅼl always be a solution in every problem.
    And when we strive hard give definitely ɑchieve οur dreams in lifetime.
    Just like in gambling, if you learn useful Powerball winning
    tips, ƅegin to help make yoսr playing mօгe exciting along witһ intensely rewarding.
    Winning this game neeԁs a reаlly good comprehensiⲟn of the alternatives and how to
    utilizе a lot of these. That is why you need function with harder,
    play smarter, and learn some taсtics about winnіng in an attempt to earn m᧐re.

    To help you with this, bec᧐ming environmentally
    friendly know tips that allow you to in defying the probabilities of Powerbaⅼl!

    Theѕe become the strateɡies which i use daily to secure. So all yοu need to do is compete with a lotto strategy,
    pick your own numbers, and play more frequent
    mеans that you raise your probabilities of winning the lottery.

    The game has other, smaller prizes as highly. The secondaгy prіzes range from $5 if you do match 2 numbers,
    in addition to the extra bowling ball., to $1500 seeking match 4 numbers, additionaly this extra Ƅasketball.

    Here is my weƄ blog: https://gizmodo.uol.com.br/lotto-th-888/

  4. Online gaming表示:

    The world of fierce gaming has undergone a remarkable revolution in recent years,
    with the rise of esports as a global sensation .
    Amidst this rapidly developing landscape, one name has emerged as a visionary – Spade Gaming.

    Spade Gaming is a influence to be reckoned
    with, a gaming establishment that has carved out a unique
    forte for itself by blending cutting-edge progress ,
    strategic planning , and a unyielding commitment to perfection .

    Established with the goal of reimagining the boundaries of
    challenging gaming, Spade Gaming has quickly become
    a emblem of freshness, driving the sector forward with its
    unconventional approach and steadfast dedication.

    At the heart of Spade Gaming’s achievement lies
    its determined attention on performer development and group building.
    The organization has cultivated an environment that
    supports and strengthens its contenders , providing them with the tools
    , guidance , and support they need to reach new zenith .

    But Spade Gaming’s weight extends far beyond the scope of the
    boundaries of the game intrinsically. The entity has also positioned
    itself as a vanguard in the domain of material
    creation, exploiting its broad collection of virtuosic experts to generate spellbinding
    and mesmerizing reporting that speaks to enthusiasts
    covering the earth .

    Aside from that, Spade Gaming’s dedication to public responsibility and public involvement differentiates
    it matchless from its competitors . The entity has
    leveraged its megaphone to support momentous drives, leveraging its influence and prominence
    to foster a consequential contribution in the landscape
    of esports and extending further .

    As the electronic sports sector soldiers on
    to evolve , Spade Gaming stands as a brilliant paragon of what can be obtained when vision , freshness, and a unwavering striving of perfection intersect .

    In the period to come , as the domain of competitive gaming presses forward to mesmerize aficionados
    and reimagine the method we involve with leisure , Spade Gaming
    will certainly remain at the leading edge , directing the crusade and crafting a pioneering era in the
    rapidly transforming world of esports.

    Also visit my blog Online gaming

  5. Milagro表示:

    14 Smart Ways To Spend Leftover Under Counter Wine Cooler
    Budget freestanding wine refrigerator (Milagro)

  6. Leopoldo表示:

    Why We Enjoy Mystery Box (And You Should, Too!) online
    mystery box websites (Leopoldo)

  7. lg freezers表示:

    Ten LG Freezers That Really Make Your Life Better
    lg freezers

  8. Take a look at my web page; hinge dating app

  9. Guide To How Much Is A Private ADHD Assessment:
    The Intermediate Guide To How Much Is A Private ADHD Assessment how much is a private Adhd assessment

  10. Think You’re Ready To Start Toyota Yaris Key Replacement?
    Answer This Question can you Track Toyota Keys

  11. You’ll Never Be Able To Figure Out This Premium Arabica Coffee Beans’s Benefits premium arabica Coffee beans

  12. I’m not sure exactly why but this website is loading incredibly
    slow for me. Is anyone else having this problem or is it a issue on my end?
    I’ll check back later on and see if the problem still exists.

  13. Drugs information sheet. Drug Class.
    pantoprazole iv vs oral
    Some about meds. Read now.

  14. You’ll Be Unable To Guess Seat Ibiza Key Fob Replacement’s Secrets Seat ibiza key fob replacement

  15. Your means of describing the whole thing in this piece
    of writing is genuinely fastidious, every one
    be able to easily understand it, Thanks a lot https://www.provenexpert.com/it-it/pub022/

  16. prostavive表示:

    Hey very nice blog!! Guy .. Beautiful .. Wonderful ..
    I will bookmark your web site and take the
    feeds also? I’m glad to seek out a lot of helpful information here within the put up, we need
    develop more strategies on this regard, thanks
    for sharing. . . . . .

  17. The 10 Scariest Things About Accident And Injury Lawyers accident and
    injury (dokuwiki.stream)

  18. Heya just wanted to give you a quick heads up and let you know a few of the images aren’t loading correctly.
    I’m not sure why but I think its a linking issue. I’ve tried it in two different internet browsers and both show the same outcome.

  19. 15 Of The Best Pinterest Boards All Time About Mesothelioma Asbestos
    Lawyers Mesothelioma Attorneys

  20. This Most Common Coffee Pods Machine Debate Isn’t As Black And White As You Might
    Think Pod Coffee Machines

  21. Why You Should Focus On Making Improvements To Repair Double Glazing Window glass repairs near me

  22. slot gacor表示:

    You are so cool! I don’t suppose I have read something like that before.
    So good to find somebody with a few unique thoughts
    on this subject. Seriously.. many thanks for starting this up.
    This website is one thing that is needed on the internet, someone
    with a bit of originality!

  23. r7表示:

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

  24. Reece表示:

    Why You Should Focus On Enhancing Key Smith For Cars car auto locksmith; Reece,

發佈留言

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