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,245,854 Responses

  1. AlbertDuM表示:

    п»їcytotec pills online: cyt premium – buy cytotec pills online cheap

  2. kontol表示:

    An outstanding share! I have just forwarded this onto a friend who had
    been conducting a little homework on this. And he in fact ordered me lunch because I found it for him…
    lol. So let me reword this…. Thanks for the meal!!
    But yeah, thanx for spending some time to discuss this issue
    here on your web page.

  3. Thanks for shedding light on this topic! I’ll be looking for a qualified top marketing agencies for law firms shortly

  4. Pol88表示:

    Greetings from Colorado! I’m bored to tears at work so I decided to check out
    your blog on my iphone during lunch break. I enjoy the
    info you provide here and can’t wait to take a look when I get
    home. I’m shocked at how fast your blog loaded on my phone ..
    I’m not even using WIFI, just 3G .. Anyhow, superb site!

  5. cuaca778表示:

    First off I want to say wonderful blog!
    I had a quick question which I’d like to ask if you
    don’t mind. I was interested to find out how you center yourself
    and clear your head before writing. I have had difficulty clearing my thoughts
    in getting my ideas out. I truly do enjoy writing
    however it just seems like the first 10 to 15 minutes are generally lost simply just
    trying to figure out how to begin. Any suggestions or tips?

    Thank you!

  6. Errol表示:

    10 Meetups On Local SEO For Small Business You
    Should Attend local services (Errol)

  7. Hi, of course this piece of writing is genuinely nice and I have
    learned lot of things from it about blogging. thanks.

  8. BrandenSlomy表示:

    canadian pharmacy amoxicillin: cheap amoxil – prescription for amoxicillin

  9. VISIT HERE表示:

    It’s amazing for me to have a site, which is valuable in favor of my knowledge.
    thanks admin

  10. DarrenUnjuh表示:

    http://iverfast.com/# stromectol ireland

  11. Sazrarr表示:

    Полезная информация как купить диплом о высшем образовании без рисков
    opengadjet.ru/diplom-dlya-uspeshnoy-kareryi-bez-lishnih-hlopot

  12. BernardMop表示:

    buy clopidogrel bisulfate buy Plavix Clo cheap plavix antiplatelet drug

  13. Sazroew表示:

    Как быстро и легально купить аттестат 11 класса в Москве
    oldmetal.ru/forum/index.php?topic=247.new#new

  14. feet fetish表示:

    Hi! Quick question that’s entirely off topic.
    Do you know how to make your site mobile friendly? My website looks weird when viewing from
    my iphone 4. I’m trying to find a template or plugin that might be able to
    resolve this issue. If you have any recommendations,
    please share. With thanks!

  15. LeonardDon表示:

    MEGA снова работает. Рабочие зеркала!!!

    https://megaweb5.top

  16. BrandenSlomy表示:

    get generic clomid price: cheap clomid – clomid without insurance

  17. Hi there colleagues, how is the whole thing, and
    what you wish for to say regarding this post, in my view its genuinely awesome designed for me.

  18. kra18 cc表示:

    Excellent post. I was checking constantly this blog and I’m impressed!
    Very helpful information specially the last part 🙂 I care for such information much.
    I was looking for this certain information for a long time.
    Thank you and best of luck.

  19. page表示:

    Wow! This blog looks exactly like my old one! It’s on a entirely different subject but it has
    pretty much the same layout and design. Wonderful choice
    of colors!

    My homepage: page

  20. seo表示:

    Heya this is somewhat of off topic but I was wondering if
    blogs use WYSIWYG editors or if you have to manually code with HTML.
    I’m starting a blog soon but have no coding know-how so I wanted to
    get guidance from someone with experience. Any help would be greatly appreciated!

  21. BrandenSlomy表示:

    buying generic clomid without dr prescription: clomid – cheap clomid

  22. When I originally commented I seem to have clicked the -Notify me when new comments are added- checkbox and
    from now on each time a comment is added I recieve 4
    emails with the same comment. Perhaps there is a means you are
    able to remove me from that service? Cheers!

  23. AlbertDuM表示:

    stromectol covid: iver fast – ivermectin cream canada cost

  24. Do you mind if I quote a couple of your posts as long as I provide credit and sources back to your webpage?
    My blog is in the very same area of interest as yours and my users would certainly benefit from a lot of the information you present here.
    Please let me know if this ok with you. Thanks a lot!

  25. Meds information leaflet. Drug Class.
    can i purchase cheap finpecia for sale
    Actual news about drug. Get now.

發佈留言

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