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,585,677 Responses

  1. PASHAReors表示:

    Тем, кто интересуется современными методами продвижения, полезно будет посетить asaplab.ru — это отличный ресурс для изучения актуальных методов продвижения./

  2. Узнай все о варикоцеле 2 степени на что влияет варикоцеле

  3. Meds information for patients. Generic Name.
    get generic keflex without prescription
    Actual trends of medication. Read now.

  4. Узнай все о варикоцеле у мужчин варикоцеле 2 степени

  5. chữ inox表示:

    wonderful points altogether, you just received a new reader.
    What may you suggest in regards to your publish that you simply made some days in the past?
    Any positive?

  6. Тут можно преобрести шкафы для оружия сейфы купить сейф для охотничьего ружья в москве

  7. What i don’t realize is in truth how you are not really
    much more smartly-liked than you might be right now. You’re very intelligent.
    You recognize therefore considerably in the case of this subject, produced
    me individually imagine it from so many various angles. Its like women and men are not interested except it is one thing to
    do with Woman gaga! Your individual stuffs great.
    All the time care for it up!

  8. Great post. I was checking constantly this weblog and I
    am inspired! Very helpful info particularly the remaining section 🙂 I handle such information a lot.
    I used to be seeking this particular information for a very long time.
    Thank you and good luck.

    https://forextrading.my.id/

  9. I’m impressed, I must say. Rarely do I come across a blog that’s equally
    educative and amusing, and let me tell you, you’ve hit the nail on the head.
    The problem is an issue that not enough men and women are speaking intelligently about.

    I am very happy I found this in my search for something relating to this.

  10. First off I would like to say great blog! I had a quick question in which I’d like to ask if you don’t mind.
    I was interested to know how you center yourself and clear your
    thoughts before writing. I’ve had a tough time clearing my thoughts in getting my ideas out.
    I do enjoy writing however it just seems like
    the first 10 to 15 minutes are usually lost simply just trying to figure out how to
    begin. Any recommendations or hints? Thanks!

  11. Nikefut表示:

    darknet drugs deep web search drug markets onion

  12. Hey there I am so thrilled I found your blog page, I really found you
    by error, while I was browsing on Yahoo for something else, Anyways I am here now
    and would just like to say thanks for a fantastic post and a all round
    thrilling blog (I also love the theme/design), I don’t have
    time to go through it all at the moment but I have book-marked
    it and also added in your RSS feeds, so when I have time I will be back
    to read a great deal more, Please do keep up the fantastic
    job.

  13. JacobLoody表示:

    https://armor-games.ru — Все о кухнях: от идей до реализации.

  14. Appreciating the dedication you put into your blog
    and detailed information you provide. It’s great to come across a blog every once in a
    while that isn’t the same old rehashed material.

    Excellent read! I’ve bookmarked your site and I’m
    including your RSS feeds to my Google account.

    https://forexlive.my.id/

  15. Seth表示:

    11 Creative Methods To Write About Leather Couches For Sale
    new couch for sale (Seth)

  16. Hello, after reading this remarkable piece of writing i am
    too cheerful to share my knowledge here with colleagues.

  17. BrandenSlomy表示:

    online order prednisone: cheap prednisone – how to get prednisone tablets

  18. WengToto表示:

    Appreciate the recommendation. ᒪet me try it ⲟut.

    Have a lοok at my website WengToto

  19. Bradleygoath表示:

    order clomid without a prescription clomid purchase online rex pharm can i buy clomid without insurance

  20. Silver water表示:

    Tremendous issues here. I’m very glad to peer your post.
    Thank you a lot and I’m having a look forward to touch you.
    Will you kindly drop me a mail?

  21. Bradleygoath表示:

    prednisone 2.5 mg daily generic Prednisone prednisone 5mg cost

  22. Nikefut表示:

    darknet drug market drug markets onion darknet site

  23. I enjoy looking through a post that will make people think.
    Also, thank you for allowing for me to comment!

  24. Dereketerm表示:

    where can i buy amoxicillin over the counter uk: amoxil – amoxicillin azithromycin

  25. Click Here表示:

    As the admin of this website is working, no hesitation very shortly it will be well-known, due to its feature
    contents.

  26. bokep表示:

    Excellent blog you have here but I was curious about if you knew of any discussion boards that cover the
    same topics talked about here? I’d really love to be a part of group where I can get
    feedback from other experienced people that share the same interest.
    If you have any suggestions, please let me know.
    Cheers!

發佈回覆給「PASHAReors」的留言 取消回覆

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