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,674,579 Responses

  1. VictorVal表示:

    casino olympe: olympe casino – olympe casino en ligne

  2. Diplomi_hiMl表示:

    купить диплом в ханты-мансийске rusdiplomm-orig.ru .

  3. VictorVal表示:

    olympe casino cresus: olympe casino avis – olympe casino cresus

  4. mostbet_liPr表示:

    мостбет кыргызстан http://www.mostbet5009.ru .

  5. mostbet_guea表示:

    мостбет кыргызстан скачать http://mostbet7004.ru/ .

  6. VictorVal表示:

    olympe casino avis: olympe – olympe

  7. Site - Si表示:

    Hey guys,

    I’ve been exploring the world of internet gambling lately, and I’ve gotta say — it’s way more exciting than I expected. At first, I was honestly suspicious. I mean, how do you even believe in an online platform with your money, right? But after digging deep (and trying out a few questionable sites so you don’t have to), I figured out a few things that distinguish a reliable casino from a complete fraud. 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 legal status (like from the MGA or the UK Gambling Commission), just run. No bonus is worth the gamble of never seeing your funds again. Also — and I know no one wants to — go through the small print. That’s the only way to know what kind of hidden traps they’ve slapped onto those so-called “amazing” bonuses.

    Now, let me share a site I’ve been playing on these last few weeks. It’s been a breath of fresh air. The interface? Super smooth. Payouts? Fast as hell. And the game selection? *Insane*. Slots, live dealers, blackjack, even some weird niche games I hadn’t tried before. Check it out here: http://oldback.66ouo.com/home.php?mod=space&uid=430356&do=profile&from=space What really impressed me was the help desk. I had a tiny issue with a bonus not working, and they got back to me in like 10 minutes. Compare that to other sites where you’re just left hanging — yeah, no thanks.

    Also, if you’re into bonuses (and who isn’t?), this place offers some awesome ones. But here’s the trick: don’t just grab every shiny offer. 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 bet the farm — please don’t. But if you’ve got a little extra fun budget and you’re looking for a bit of online excitement, online casinos can totally deliver. Just keep your head on, set a budget, 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 interested or trying to find a good place to play. If you’ve got your own stories or even some casino nightmares, I’m all ears — love talking shop about this stuff.

    Good luck out there, and spin smart, win big ??

  8. AlbertShund表示:

    https://olympecasino.pro/# olympe casino cresus

  9. Williamwhogs表示:

    olympe casino: casino olympe – olympe

  10. Sazrsde表示:

    Приобрести диплом под заказ возможно через официальный портал компании. redebuck.com.br/read-blog/33432_kupit-diplom-s-zaneseniem-v-reestr-stoimost.html

  11. Gregoryron表示:

    olympe: olympe casino avis – olympe casino en ligne

  12. Sazrhys表示:

    Приобрести диплом на заказ вы сможете через официальный портал компании. cvbankye.com/employer/frees-diplom

  13. Treffcn表示:

    Выгодно купить диплом о высшем образовании. Покупка документа о высшем образовании через проверенную и надежную фирму дарит ряд плюсов для покупателя. Такое решение помогает сэкономить как длительное время, так и значительные средства. sport-faq.ru/kupit-diplom-garantii-i-konfidentsialnost

  14. гарантия при продаже аккаунтов marketplace-akkauntov-top.ru

  15. Trefmie表示:

    Заказать диплом любого университета. Заказ подходящего диплома через качественную и надежную компанию дарит много преимуществ. Такое решение дает возможность сберечь как дорогое время, так и значительные финансовые средства. angelladydety.getbb.ru/posting.php?mode=post&f=46&sid=2afa959c7ec3b6898f36779ce362ecde

  16. I’ll immediately take hold of your rss as I can’t find your e-mail subscription hyperlink or e-newsletter service. Do you have any? Kindly allow me recognize so that I may just subscribe. Thanks.

  17. Williamwhogs表示:

    olympe casino cresus: olympe casino cresus – olympe

  18. Ahaa, its pleasant conversation on the topic of this piece of writing here at this
    blog, I have read all that, so now me also commenting here.

    Here is my web page: สมัครหวย RUAY

  19. Robertexexy表示:

    This article presents the Top 10 online casinos in Russia, which offer an impressive selection of games, generous bonuses and safe conditions for players. Read on to find the perfect entertainment platform!

  20. маркетплейс игровых аккаунтов https://marketplace-akkauntov-top.ru

發佈回覆給「melbet_zckl」的留言 取消回覆

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