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

  1. Good information. Lucky me I discovered your blog by accident (stumbleupon).
    I’ve book marked it for later! https://Asiapipeline.com/?document_srl=716291

  2. RobertJar表示:

    3000mg prednisone: Predni Best – prednisone 30 mg

  3. hiop表示:

    Fine Dining hiop

  4. porno表示:

    What’s up i am kavin, its my first time to commenting anywhere, when i
    read this paragraph i thought i could also make comment due
    to this sensible post.

  5. Noah Glover表示:

    This is quite enlightening. Check out local dumpster rental in McLeansville for more

  6. The Top Top Asbestos Attorney The Gurus Have Been Doing Three Things Mesothelioma attorney

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

  8. Предлагаем услуги профессиональных инженеров офицальной мастерской.
    Еслли вы искали ремонт стиральных машин siemens рядом, можете посмотреть на сайте: ремонт стиральных машин siemens адреса
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  9. sga123表示:

    Pretty nice post. I just stumbled upon your blog and wished
    to say that I’ve really enjoyed browsing your blog posts.
    In any case I will be subscribing to your rss feed and I
    hope you write again soon!

  10. Nikefut表示:

    darknet markets 2024 the dark internet tor markets

  11. RobertJar表示:

    amoxicillin 775 mg: amoxicillin 50 mg tablets – how to buy amoxicillin online

  12. Manuel Nelson表示:

    I found my personal injury attorneys near me through recommendations

  13. sga123表示:

    Undeniably believe that which you said. Your favorite justification appeared to be on the net the simplest thing
    to be aware of. I say to you, I definitely get irked while people consider
    worries that they plainly do not know about. You managed
    to hit the nail upon the top and also defined out the whole thing without having side effect , people could
    take a signal. Will probably be back to get more. Thanks

  14. Medication information leaflet. Long-Term Effects.
    buying generic cozaar no prescription
    All trends of drug. Read information here.

  15. Mattie Rhodes表示:

    After my car accident, I was skeptical about chiropractic care Chiropractor for soft tissue injuries from car accident

  16. There are no barriers based on gender, skin colour, skin type or age.

  17. RobertJar表示:

    ciprofloxacin 500 mg tablet price: ciprofloxacin order online – cipro pharmacy

  18. RobertJar表示:

    ciprofloxacin 500mg buy online: ciprofloxacin 500 mg tablet price – ciprofloxacin over the counter

  19. Bessie Romero表示:

    I’m preparing to visit Lake Ouachita quickly for some boating fun! It is among my favorite spots in Arkansas. Get tips on water activities at news protection

  20. DanielAbice表示:

    http://cipharmdelivery.com/# buy cipro online usa

  21. Nikefut表示:

    deep web search dark web search engine dark web search engines

  22. EdgarWat表示:

    Интересные статьи о займах – https://vladnews.ru/2023-11-28/228457/pochemu_oformit

  23. Caleb Douglas表示:

    This was highly useful. For more, visit restaurants near me

  24. Roxie Knight表示:

    Este important să ai alături un partener de încredere în aceste momente pompe funebre

  25. Porn Sex表示:

    Pretty section of content. I just stumbled upon your web site and in accession capital to assert that I get in fact enjoyed account your blog
    posts. Anyway I’ll be subscribing to your augment and even I achievement you access consistently rapidly.

  26. DichaelDax表示:

    Hello there! Do you use Twitter? I’d like to follow you if that would be okay. I’m definitely enjoying your blog and look forward to new updates.

    https://fsris.org.rs/news/code-promo-22bet.html

發佈留言

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