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,479,484 Responses

  1. Thank you for the good writeup. It in reality was once a amusement account it.
    Glance complicated to far delivered agreeable from you! However,
    how could we keep in touch?

  2. I am regular visitor, how are you everybody? This post posted at this web site is
    actually good.

    my page … Ultra K9 Pro Reviews

  3. Hi there just wanted to give you a quick heads up.
    The text in your article seem to be running off the screen in Chrome.
    I’m not sure if this is a formatting issue or something to do
    with browser compatibility but I figured I’d post to let you
    know. The layout look great though! Hope you get the problem resolved
    soon. Thanks

  4. Usually I don’t read article on blogs, but I would like to say that this write-up very compelled me to try and do so!
    Your writing style has been amazed me. Thanks, very great article.

  5. op表示:

    Relaxation Therapy op

  6. kra17.at表示:

    It’s going to be end of mine day, except before end I am reading this great post to increase my knowledge.

  7. Nikefut表示:

    darknet drug store tor market url dark internet

  8. Attractive section of content. I just stumbled upon your web site and in accession capital to assert that I get in fact loved account your blog posts.
    Any way I will be subscribing for your feeds or even I fulfillment you get admission to persistently rapidly.

    Feel free to surf to my web blog … article source

  9. although it can occur at age 16 or not until age 76.The bio-medical treatment goal is to reestablish predictable erection and intercourse by using Viagra or penile injections.ラブドール エロ

  10. nodeposit表示:

    What’s Happening i am new to this, I stumbled
    upon this I have found It absolutely useful and it has helped
    me out loads. I hope to contribute & assist other users like its aided me.
    Good job.

  11. It’s awesome to pay a quick visit this web page and reading
    the views of all colleagues regarding this piece of writing, while I am also
    zealous of getting experience.

  12. Nikefut表示:

    dark web search engine dark website darkweb marketplace

  13. Eric Turner表示:

    I love how virtual marketing corporations can tailor solutions to are compatible the several industries SEO Agency

  14. Ivoryvioth表示:

    Существует несколько типов систем противодымной вентиляции, которые отличаются по принципу работы и функциональным возможностям:
    Зависимость от внешних условий: Качество вентиляции зависит от температуры воздуха, влажности и ветра.
    Торговые центры
    * **Вытяжная**: удаление загрязненного воздуха из помещения. Применяется для удаления вредных веществ, дыма, пара и других загрязнений.
    Управляющая компания: главный “”дирижер”” вентиляции

    germecmetal.ru

  15. Click here表示:

    It’s great that you are getting ideas from this article as well as from our argument made here.

  16. Meds information sheet. Long-Term Effects.
    where to buy generic valtrex without rx
    Everything news about medicines. Read now.

發佈留言

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