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,433,200 Responses

  1. Good write ups Appreciate it.

  2. %%

    Feel free to surf to my web blog: Replacing Volkswagen Key,
    Frank-Byrne-2.Blogbright.Net,

  3. Hi, i feel that i noticed you visited my web site
    so i came to go back the want?.I am trying to find issues to enhance
    my web poker site rankings!I
    suppose its ok to use some of your ideas!!

  4. What a information of un-ambiguity and preserveness
    of precious knowledge concerning unexpected feelings.

  5. DonnaRaila表示:

    Vavada casino играть
    https://nailpub.ru/forum/members/kiper4ukyu.95761/#about
    Не забывайте, что Казино Вавада предлагает не только возможность играть на деньги, но и испытать удачу в бесплатных режимах. Это отличная возможность потренироваться перед серьезной игрой и раскрутить барабаны в слоты-онлайн в том режиме, который Вам по душе.Добро пожаловать в захватывающий мир азарта и увлекательных игр на официальном сайте — Казино Вавада! Если вы готовы окунуться в водоворот невероятных эмоций и испытать удачу в самых захватывающих онлайн-слотах, то Вавада Казино — ваш идеальный выбор.

  6. Lashawn表示:

    %%

    My homepage; csgo case battles (Lashawn)

  7. Quyen表示:

    upvc sash windows gravesend (Quyen)

  8. I like this web site because so much useful material
    on here :D.

    Feel free to surf to my page … Tiny House Builders (1-800-plumber.co)

  9. Today, I went to the beach front with my kids.
    I found a sea shell and gave it to my 4 year old daughter
    and said “You can hear the ocean if you put this to your ear.” She placed the shell to her ear and screamed.
    There was a hermit crab inside and it pinched her
    ear. She never wants to go back! LoL I know this is totally off topic
    but I had to tell someone!

  10. You should be a part of a contest for one of the finest blogs on the net.
    I will highly recommend this blog!

  11. My brother suggested I might like this web site.
    He was entirely right. This put up actually made my day.
    You can not consider just how a lot time I
    had spent for this info! Thank you!

  12. Hi, i feel that i noticed you visited my blog so i came to return the prefer?.I’m attempting to find
    things to enhance my web site!I assume its good enough to make use of a few of your ideas!!

    Here is my web page hookup near me

  13. %%

    Take a look at my blog post – Suzuki Keys; http://Www.Remat.Eco.Br,

  14. I will immediately seize your rss as I can’t in finding your
    e-mail subscription hyperlink or e-newsletter service.
    Do you’ve any? Kindly let me realize so that I may subscribe.
    Thanks.

    my web-site … facebook for sex

  15. %%

    Here is my web site … Electricians In

  16. Jake表示:

    %%

    my blog :: how to get case csgo, Jake,

  17. online slots表示:

    Do you mind if I quote a few of your posts
    as long as I provide credit and sources back to your website?
    My blog is in the exact same area of interest as yours and my visitors would really
    benefit from a lot of the information you present here.
    Please let me know if this ok with you. Many thanks!

    My page: online slots

  18. slots online表示:

    I think that is one of the such a lot significant info for me.
    And i am glad studying your article. But want to statement on few basic issues, The site taste is perfect, the articles is in point of fact great : D.
    Good task, cheers

    Here is my web page :: slots online

  19. %%

    Also visit my webpage :: Renault Key Card

  20. LABORKITTEL表示:

    Hi my loved one! I want to say that this post is awesome, nice written and
    come with approximately all significant infos. I would like to look
    extra posts like this .

    Also visit my web site – LABORKITTEL

  21. essay help表示:

    I’m gone to convey my little brother, that he
    should also go to see this webpage on regular basis to obtain updated from
    newest news.

  22. Irving表示:

    %%

    Stop by my website – buy broad spectrum cbd oil; Irving,

  23. Telegra.Ph表示:

    %%

    Feel free to visit my web blog: Legit Csgo Case
    Sites (Telegra.Ph)

發佈留言

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