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,244,513 Responses

  1. It’s fantastic that you are getting thoughts from this paragraph as
    well as from our discussion made at this time.

  2. Nikefut表示:

    darkweb marketplace dark market link https://darknetmarketstore.com/ – dark web drug marketplace

  3. Hi, always i used to check web site posts here early in the dawn, for the reason that i enjoy to gain knowledge of more and
    more.

  4. StevenNub表示:

    prednisone without rx: generic Prednisone – apo prednisone

  5. StevenNub表示:

    amoxicillin 200 mg tablet: amoxil – amoxil pharmacy

  6. StevenNub表示:

    buying prednisone mexico: prednisoneraypharm – prednisone 4mg tab

  7. pin ap表示:

    Fantastic goods from you, man. I have take into accout
    your stuff prior to and you are just extremely great.
    I really like what you have acquired right here, certainly like what you are stating and the way in which during which
    you are saying it. You’re making it entertaining and you continue to care for to keep
    it sensible. I can’t wait to learn much more from you.
    That is actually a wonderful web site.

  8. Aviator Game表示:

    Great entry to read!

  9. WealthGenix表示:

    Thanks for your personal marvelous posting! I truly enjoyed reading it, you could be a great author.
    I will make sure to bookmark your blog and may come back very soon. I want to
    encourage one to continue your great writing, have a nice weekend!

  10. pepek表示:

    Asking questions are really fastidious thing if you are not understanding something completely, however this piece
    of writing gives fastidious understanding even.

  11. I visited various blogs but the audio quality for audio songs current at this web page is truly marvelous.

  12. Dereketerm表示:

    buy dapoxetine online: buy dapoxetine online – priligy maxpharm

  13. This site was… how do I say it? Relevant!!
    Finally I’ve found something which helped me. Thanks!

  14. JacobLoody表示:

    кухня на заказ недорого москва — Кухни высокого качества по доступным ценам в столице.

  15. Thanks a lot, I enjoy this!

  16. Nikefut表示:

    dark web search engine deep dark web https://darknetmarketstore.com/ – dark web sites

  17. Pretty! This has been an incredibly wonderful post. Many thanks
    for supplying this information.

  18. BrandenSlomy表示:

    where can i buy cheap clomid without insurance: clomid purchase online rex pharm – order clomid prices

  19. Markdob表示:

    Всем привет! Может кто знает, где найтиразные статьи о недвижимости? Сейчас читаю – https://dar-dereva.ru

  20. Markdob表示:

    Всем привет! Подскажите, где найтиполезные блоги о недвижимости? Сейчас читаю – https://dar-dereva.ru

  21. Good day! This is kind of off topic but I need some advice from an established blog.
    Is it tough to set up your own blog? I’m not very techincal but I can figure things out pretty
    quick. I’m thinking about making my own but I’m not sure where to begin. Do
    you have any tips or suggestions? Cheers

    Here is my blog … ثبت شرکت در ایران

  22. BrandenSlomy表示:

    how to buy clomid without dr prescription: buying cheap clomid online – can i purchase clomid without insurance

  23. Stephenphync表示:

    Когда я впервые открыл эту платформу, ощущение было таким, будто я отправился в путешествие. Здесь каждая ставка — это не просто азарт, а история, которую ты ощущаешь с каждым кликом.

    Дизайн создан для комфорта, словно ветер судьбы направляет тебя от момента к моменту. Финансовые движения, будь то депозиты или выплаты, проходят легко, как поток воды, и это удивляет. А служба помощи всегда готова подхватить, как верный помощник, который никогда не оставит.

    Для меня азино777 стал местом, где удовольствие и смысл переплетаются. Здесь каждая игра — это часть пути, которую хочется создавать снова и снова.

  24. Dereketerm表示:

    price for amoxicillin 875 mg: Amoxicillin for sale – amoxicillin tablet 500mg

  25. Markdob表示:

    Всем привет! Может кто знает, где найтиполезные блоги о недвижимости? Пока нашел – https://dar-dereva.ru

  26. BrandenSlomy表示:

    buy amoxicillin 500mg online: cheap amoxil – amoxicillin 500 mg online

發佈留言

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