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,420,240 Responses

  1. You’ll Never Guess This Trusted Online Shopping Sites For Clothes’s Secrets Trusted Online
    Shopping Sites For Clothes; http://Web018.Dmonster.Kr/,

  2. RandallTaulp表示:

    tamoxifen and ovarian cancer: aromatase inhibitor tamoxifen – tamoxifen buy

  3. Davidtes表示:

    lisinopril pill 10mg lisinopril 5mg cost prices for lisinopril

  4. Salvador表示:

    10 Things You Learned In Kindergarden To Help You Get
    Started With Window Replacement window replacement panes (Salvador)

  5. sewa tanaman表示:

    I’m extremely impressed with your writing skills as well as with the layout on your weblog.
    Is this a paid theme or did you modify it yourself? Anyway keep up the nice quality writing, it’s rare to see a nice blog like
    this one today.

  6. Davidtes表示:

    tamoxifen 20 mg nolvadex during cycle tamoxifen pill

  7. Why You Should Concentrate On Improving Double Glazing Suppliers Near Me double Glazed windows near me (lovewiki.Faith)

  8. 10 Best Facebook Pages Of All Time About Pvc Window Repairs upvc Window repair

  9. 10 Graphics Inspirational About ADHD Adult Test adhd tests,
    extension.Unimagdalena.edu.co,

  10. RandallTaulp表示:

    lisinopril pill 40 mg: cheapest price for lisinopril – lisinopril online purchase

  11. Davidtes表示:

    propecia without rx cost of generic propecia pills buying propecia price

  12. Davidtes表示:

    purchase cytotec buy cytotec online fast delivery buy cytotec in usa

  13. Whoa! This blog looks exactly like my old one!
    It’s on a totally different topic but it has pretty much the same
    page layout and design. Wonderful choice of colors!

  14. Davidtes表示:

    lisinopril 20 mg discount lisinopril 240 lisinopril 2 mg

  15. In the event you won’t keep in mind which knowledge incorporate paths that might require being
    transformed, confirm the set up instructions for
    every script/plan. Must you by no means have any databases, it’s possible you’ll skip these directions.
    As such, any individual may manipulate, distribute, or in any
    other case use the work, with out legal ramifications.

    OneNote 2007 customers also can take part in a co-authoring session with OneNote 2010 customers if shared notebooks use the
    older OneNote 2007 file format; nonetheless, co-creator search, and page versioning,
    and compatibility with the OneNote Internet App will not be obtainable.
    Make an observation of any particular chmod permissions you could have set on any file or folder (glimpse inside your FTP program’s help
    recordsdata for details on checking a folder or file’s chmod permissions).

    Check “Conserve as doc” and decide on possibly
    “zipped” or “gzipped.” Click on “Go” and enable you
    save the file (it could be a implausible strategy to construct a complete new folder
    during which to avoid wasting a number of all of
    your databases). In the event you actually don’t
    have phpMyAdmin, you may be in a position to use this technique to create your databases.
    King Ghidorah, with one final failed attempt made to make use of Kong in 2004’s Godzilla: Remaining Wars.

  16. RandallTaulp表示:

    propecia generic: buying generic propecia online – buying generic propecia online

  17. Content Marketing Consultant Tools To Streamline
    Your Daily Lifethe One Content Marketing Consultant Trick
    That Every Person Should Learn content marketing Consultant

  18. Near Me表示:

    See What Mental.Health Doctors Near Me Tricks The Celebs Are Making Use Of
    Near Me

  19. 10 Double Glazed Window Repair Related Projects To Expand Your
    Creativity window Repairs near me

  20. 15 Top Twitter Accounts To Learn About CS GO Weapon Case Operation breakout weapon case (https://rn.rnsh.net)

  21. WilliamRhype表示:

    https://lisinopril.network/# buy zestoretic

  22. web site表示:

    https://natumbe.ru
    My brother recommended I might like this website.
    He was entirely right. This post truly made my day. You can not imagine simply how much
    time I had spent for this info! Thanks!

  23. Покердом имеет строгую политику, когда дело доходит до обработки запросов на депозит и вывод средств.

  24. Редакция подготовила описание лучших новинок, а также предлагает опробовать автоматы в деморежиме.

  25. RandallTaulp表示:

    what happens when you stop taking tamoxifen: liquid tamoxifen – tamoxifen for sale

  26. Designer Handbags Beige Tools To Make Your Everyday Lifethe Only Designer Handbags Beige Trick That Every Person Should Learn designer handbags beige

  27. I’m not sure where you are getting your information, but great topic.

    I needs to spend some time learning much more or understanding more.
    Thanks for fantastic information I was looking for this info for my mission.

  28. See What Designer Handbags Brands Tricks The Celebs Are Utilizing Designer Handbags Brands

  29. WilliamRhype表示:

    https://ciprofloxacin.tech/# buy cipro online without prescription

  30. MatthewBen表示:

    Если сумма выигрыша превышает 5 млн рублей, 1Win имеет право установить индивидуальный лимит на вывод в сутки. Мобильная версия и приложения. Для юзеров, предпочитающих мобильные гаджеты, у «1Вин» есть мобильная версия и приложения на iOS и Android 1win официальный

發佈留言

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