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,686,228 Responses

  1. Definitely consider that that you stated. Your favorite reason seemed to be at the internet the simplest
    factor to be aware of. I say to you, I certainly get annoyed even as other folks think about issues that they plainly
    don’t recognize about. You managed to hit the nail upon the top and
    also outlined out the entire thing with no need side-effects , folks can take a signal.
    Will likely be back to get more. Thank you

    Here is my web blog: reviews on the memory wave

  2. red on bet表示:

    Optimizing Online Casinos with Contextual Insights
    Contextual Insights for Optimizing Online Casinos
    In the competitive sphere of virtual betting,
    understanding user behavior and preferences is paramount.
    Many operators are turning to data-driven techniques to fine-tune their offerings, ensuring players receive personalized
    experiences that resonate with their interests.
    By leveraging analytics, platforms can identify key trends and adapt their content accordingly.

    Behavioral analytics play a pivotal role in shaping gameplay experiences.
    By monitoring player interactions, operators can pinpoint which games
    attract attention and which features are frequently utilized.

    Such insights enable the creation of tailored promotions
    that directly appeal to active participants, enhancing satisfaction and retention rates.

    Another strategic avenue involves content adaptation. Offering localized
    games and bonuses not only caters to regional preferences
    but also fosters a sense of community among players.
    This approach can significantly boost engagement levels and
    encourage frequent visits as customers feel a deeper connection to
    the platform.
    By prioritizing data analysis and community-focused content,
    operators can stand out in a saturated market.
    Implementation of these methods serves to create a
    more engaging and responsive environment, ultimately driving long-term success.

    Utilizing Player Behavior Data for Tailored Gaming Experiences
    Understanding player behavior is crucial for crafting personalized gaming
    experiences. By analyzing patterns such as time spent on games, betting amounts, and game preferences, operators can customize offerings that resonate with individual players.

    For instance, tracking session duration can indicate player engagement levels.

    Players who favor quick sessions might appreciate shorter, fast-paced games with
    instant outcomes. Conversely, those who invest longer periods may be inclined towards immersive
    experiences that involve strategic planning and progression.
    Betting habits provide further insights. For players who typically place lower stakes, offering promotions or games emphasizing
    lower buy-ins can enhance their experience while encouraging more
    frequent participation. High rollers, on the other hand, can be targeted with
    exclusive bonuses and high-stakes tournaments that cater to their preferences.

    Geolocation data can enhance this personalization approach.

    Specific regions may showcase distinct gaming trends.
    By harnessing this data, a casino could curate special
    events or promotions that align with local tastes, thus
    optimizing player engagement and satisfaction.
    Implementing a loyalty program tailored to playing styles also drives retention. For example, players who focus on table games could receive rewards based on milestones achieved in games like blackjack
    or roulette. This strategy not only incentivizes continued play but also fosters
    a sense of community among players with similar interests.

    The integration of AI-driven recommendations can enhance this further.
    By utilizing machine learning algorithms,
    platforms can suggest games based on historical data, ensuring players
    are consistently presented with options that match their tastes.

    In conclusion, leveraging player behavior analytics not only refines the gaming experience but
    also maximizes engagement and retention. Operators who can effectively harness
    these insights will likely see improved player loyalty and increased revenue.

    Integrating Real-Time Analytics to Enhance User Engagement
    Incorporating real-time analytics into platform operations significantly boosts user participation and satisfaction. By monitoring player behavior and preferences instantly,
    operators can tailor experiences that resonate more deeply with
    individuals.
    Utilizing data points such as session duration, game variety preferences, and payout frequency can inform targeted promotions.
    For instance, if analytics reveal that a user frequently engages with slot machines, personalized bonuses red on bet related games can increase retention and attract repeat visits.

    Heatmaps illustrating user interactions within platforms
    can guide intuitive design adjustments. Understanding where players spend the most time
    allows for strategic placement of features like chat
    support, live tournaments, or loyalty programs, enhancing the
    gaming experience.
    Implementing notifications based on real-time data also proves beneficial.
    Informing users about special events or achievements during their
    gaming sessions fosters a sense of community and urgency.
    Tailored messages can prompt immediate action, whether
    it’s joining a live game or participating in a flash sale.

    Furthermore, incorporating A/B testing methodologies via real-time user data can optimize
    user interfaces and functionalities. Testing different layouts or promotional strategies with
    selected player segments allows operators to identify the most appealing options quickly,
    enhancing overall engagement.
    Lastly, integrating social elements influenced by real-time
    trends can create a vibrant atmosphere. Elements such as live leaderboards or real-time chat can cultivate interaction among users, transforming solitary gaming into a communal experience, thereby
    driving higher engagement metrics.

  3. VictorVal表示:

    olympe casino: olympe – olympe

  4. Sazrhqw表示:

    Купить диплом института по невысокой цене возможно, обратившись к надежной специализированной фирме. Купить документ института можно у нас в Москве. buldingnews.ru/diplomyi-s-vyisokim-urovnem-zashhityi

  5. Diplomi_kpMl表示:

    купить диплом о высшем образовании в ульяновске rusdiplomm-orig.ru .

  6. mostbet_iqea表示:

    mostbet kg скачать на андроид https://mostbet7004.ru .

  7. If you want to get some action, visit our American HD
    video sex area.

  8. mostbet_unPr表示:

    скачать мостбет https://mostbet5009.ru/ .

  9. madridbet表示:

    I like the valuable information you supply oon yolur articles.
    I’ll bookmark your blog and check again right here frequently.

    I’m moderately certain I’ll be informed plenty off new stuff proper right
    here! Good luck for the following!

    my web-site – madridbet

  10. Williamwhogs表示:

    olympe casino cresus: olympe casino – olympe casino en ligne

  11. mostbet_ivea表示:

    скачать мостбет скачать мостбет .

  12. eliteflix表示:

    Great delivery. Great arguments. Keep up the amazing effort.

  13. Howdy! I know this is kinda off topic however , I’d figured I’d ask.

    Would you be interested in exchanging links or maybe guest authoring a blog post or vice-versa?
    My website discusses a lot of the same subjects as yours and I feel we could greatly benefit from each other.
    If you might be interested feel free to shoot me an e-mail.
    I look forward to hearing from you! Awesome blog by the way!

  14. Ronaldbet表示:

    olympe casino avis olympe casino cresus

  15. Williamwhogs表示:

    olympe casino en ligne: olympe casino – olympe casino avis

  16. keobongviptop表示:

    I have read so many articles on the topic of the blogger lovers
    however this piece of writing is truly a nice piece of writing,
    keep it up.

  17. Gregoryron表示:

    casino olympe: olympe – casino olympe

  18. Cazryts表示:

    Мы предлагаем дипломы любой профессии по невысоким ценам. Купить диплом в Копейске — kyc-diplom.com/geography/kopejsk.html

  19. Site - Si表示:

    Hey people,

    I’ve been checking out the world of online casinos lately, and I’ve gotta say — it’s way more exciting than I expected. At first, I was totally unsure. I mean, how do you even trust an online platform with your hard-earned money, right? But after digging deep (and trying out a few sketchy sites so you don’t have to), I figured out a few things that set apart a legit casino from a total scam. First off, if you’re new to all this, here’s the golden rule: **regulation is key**. If a casino doesn’t have a proper license (like from the Malta Gaming Authority or the UKGC), just close that tab. No bonus is worth the trouble of never seeing your funds again. Also — and I know no one wants to — read the T&Cs. That’s the only way to know what kind of playthrough limits they’ve slapped onto those so-called “amazing” bonuses.

    Now, let me share a site I’ve been using these last few weeks. It’s been a breath of fresh air. The interface? Super smooth. Payouts? Quick — like 24 hours quick. And the game selection? *Wild*. Slots, live dealers, blackjack, even some oddball options I hadn’t tried before. Check it out here: https://mensclinicblog.co.za/mens-clinic-groblerpark/ What really impressed me was the customer service. I had a tiny issue with a bonus not working, and they got back to me in like instantly. Compare that to other sites where you’re just left hanging — yeah, not worth it.

    Also, if you’re into bonuses (and who isn’t?), this place offers some legit ones. But here’s the trick: don’t just chase bonuses. It’s smarter to go for fair terms than a huge bonus you’ll never be able to withdraw. I’m not saying you should go and blow your whole paycheck — please don’t. But if you’ve got a little extra fun budget and you’re looking for a chill way to spend an evening, online casinos can totally deliver. Just play smart, control your bankroll, and don’t treat it like a side hustle. It’s for fun, not for a paycheck. Anyway, just wanted to drop my experience here in case anyone’s curious or trying to find a good place to play. If you’ve got your own recommendations or even some wild losses, I’m all ears — love talking shop about this stuff.

    Good luck out there, and don’t let the house win too much ??

  20. Gregoryron表示:

    olympe casino avis: olympe casino avis – olympe

  21. Jazlykiff表示:

    Играйте в азартные игры и ставки на спорт в мостбет casino – современном онлайн-казино с широким выбором игровых автоматов и привлекательными бонусами для игроков.

  22. Warm hot blue movie video is what this is everything about, aren’t it?

  23. Williamwhogs表示:

    olympe casino en ligne: olympe casino – olympe casino cresus

  24. I don’t know if it’s just me or if everybody else experiencing problems with your
    site. It seems like some of the written text within your content are running off the screen. Can someone
    else please provide feedback and let me know if this is happening to
    them as well? This may be a issue with my browser because I’ve had this happen previously.
    Thanks

  25. VictorVal表示:

    olympe casino: olympe casino en ligne – olympe casino

發佈留言

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