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,482,172 Responses

  1. Josephmax表示:

    https://pinup-kazi.kz/# pin up казино

  2. HenrydeT表示:

    вавада вавада вавада казино онлайн

  3. Josephmax表示:

    http://pinup-kazi.ru/# pinup-kazi.ru

  4. Sazroiz表示:

    Диплом вуза купить официально с упрощенным обучением в Москве

    mireait.listbb.ru/viewtopic.php?f=2&t=730

  5. DarioTob表示:

    vavada: вавада онлайн казино – казино вавада

  6. Hi it’s me, I am also visiting this site on a regular basis, this web page is in fact nice and
    the visitors are really sharing nice thoughts.

  7. Hi! I’ve been reading your web site for a while now and finally got the bravery to go ahead and
    give you a shout out from Humble Texas! Just wanted
    to mention keep up the great work!

    Also visit my web blog :: Diabetic foot care Seattle

  8. Sazrkpj表示:

    Аттестат 11 класса купить официально с упрощенным обучением в Москве

    toplentanews.ru/ofitsialnyiy-diplom-bez-lishnih-usiliy-prosto-i-byistro

  9. Jamesdiure表示:

    пинап казино: пин ап казино официальный сайт – пин ап казино официальный сайт

  10. Jamesdiure表示:

    pinup: pinup – пин ап вход

  11. Sazrgxr表示:

    Всё, что нужно знать о покупке аттестата о среднем образовании без рисков

    mystroycenter.ru/kupite-diplom-i-nachnite-uspeshnuyu-kareru-pryamo-seychas

  12. Sazruxm表示:

    Как избежать рисков при покупке диплома колледжа или ПТУ в России

    cozy.moibb.ru/viewtopic.php?f=31&t=8236

  13. milf porn表示:

    Do you have a spam issue on this website;
    I also am a blogger, and I was wanting to know your situation; many of us have developed some
    nice methods and we are looking to swap solutions with others, please shoot me an email if interested.

  14. Sazrfzv表示:

    Реально ли приобрести диплом стоматолога? Основные этапы

    study.flybb.ru/viewtopic.php?f=4&t=777

  15. Do Greens and crossbenchers who claim that transparency and integrity is at
    the heart of their reason for entering Parliament in the first place hear themselves?

    In the past few days they have mounted self-serving arguments
    against proposed electoral reforms that the major parties look
    set to come together to support.

    The reforms include caps for how much money wealthy individuals can donate, caps on the amount candidates
    can spend in individual electorates to prevent the equivalent of an arms race, and
    a $90million limit on what any party can spend at an election – actually
    less than the major parties currently spend.

    The proposed new laws also include lower disclosure thresholds for donations, thus increasing the transparency of who makes political donations in the first place.

    So the wealthy wont be able to hide behind
    anonymity while using their cash to influence election outcomes – and the extent to which they can use their wealth at all will be limited.

    The bill will further improve transparency by also increasing the speed and
    frequency that disclosures of donations need to be made.

    At present we have the absurd situation in which donations get made – but you only find out the details of who
    has given what to whom many months later, well after elections are won and lost.

    In other words, what is broadly being proposed will
    result in much greater transparency and far less big money
    being injected into campaigning by the wealthy.

    Teal Kylea Tink claimed the major parties were ‘running scared’ with the policy and warned the reform would ‘not stop the rot’ 

    Greens senate leader Larissa Waters (left) fired a warning shot – saying if it serves only the major
    parties ‘it’s a rort, not reform’. Teal independent ACT senator David Pocock (right)
    said: ‘What seems to be happening is a major-party stitch-up’

    Anyone donating more than $1,000 to a political party, as opposed to $16,000 under the current rules,
    will need to disclose having done so. And how much they can donate
    will be capped.

    Yet the Greens and Teals have quickly condemned the proposed new
    laws, labeling them a ‘stitch-up’, ‘outrageous’ and ‘a rort, not a
    reform’. 

    They have lost their collective minds after finding out that Labor’s
    proposal just might secure the support of the opposition.

    I had to double check who was criticising what exactly
    before even starting to write this column.

    Because I had assumed – incorrectly – that these important transparency measures stamping out the influence of the wealthy must have been proposed by
    the virtue-signalling Greens or the corruption-fighting Teals, in a united
    crossbench effort to drag the major parties closer
    to accountability.

    More fool me.

    The bill, designed to clean up a rotten system,
    is being put forward by Labor and is opposed by a growing cabal of crossbenchers.

    It makes you wonder what they have to hide. Put simply, the Greens and Teals doth protest too much on this issue.

    Labor is thought to be trying to muscle out major political donors such as Clive Palmer

    Another potential target of the laws is businessman and Teal funder Simon Holmes à
    Court

    The Greens have taken massive donations in the past, contrary to their irregular calls to tighten donations rules (Greens leader
    Adam Bandt and Senator Mehreen Faruqi are pictured)

    The major parties have long complained about the influence the likes of Simon Holmes à Court wields behind the scenes amongst the Teals. 

    And we know the Greens have taken massive donations from the
    wealthy in the past, contrary to their irregular calls to tighten donations rules.

    Now that tangible change has been proposed, these bastions of virtue are running a mile from reforms that will curtail
    dark art of political donations.

    The Labor government isn’t even seeking for these transparency
    rules to take effect immediately, by the
    way. It won’t be some sort of quick-paced power play before the next election designed to catch the crossbench out.

    They are aiming for implementation by 2026, giving everyone
    enough time to absorb and understand the
    changes before preparing for them.

    Don’t get me wrong, no deal has yet been done between Labor
    and the Coalition. I imagine the opposition want to go over the laws with a fine tooth comb.

    As they should – because it certainly isn’t beyond
    Labor to include hidden one-party advantages in the proposed
    design which would create loopholes only the unions are capable of
    taking advantage of, therefore disadvantaging the Coalition electorally in the years to come.

    But short of such baked-in trickiness scuttling a deal to get these proposed laws implemented, the crossbench should offer their support, not cynical opposition, to what is being advocated for.

    They might even be able to offer something worthwhile that could
    be incorporated in the package.

    To not do so exposes their utter hypocrisy and blowhard false commentary about
    being in politics to ‘clean things up’.

  16. DarioTob表示:

    вавада казино зеркало: вавада казино зеркало – вавада онлайн казино

  17. I am really enjoying the theme/design of your web site. Do
    you ever run into any internet browser compatibility problems?
    A few of my blog visitors have complained about my site not operating correctly in Explorer but looks great in Chrome.

    Do you have any recommendations to help fix this problem?

  18. Lida Mann表示:

    Helpful suggestions! For more, visit roof repair

發佈留言

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