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,024 Responses

  1. Great site you have here.. It’s difficult to find high-quality writing
    like yours nowadays. I seriously appreciate people like you!
    Take care!!

  2. Markdob表示:

    Приветствую. Подскажите, где почитатьполезные статьи о недвижимости? Пока нашел – https://avgust-shop.ru

  3. Incredible! This blog looks just like my old one! It’s on a totally different subject but it has pretty much the same page layout
    and design. Outstanding choice of colors!

  4. hello88表示:

    First off I would like to say excellent blog! I had a quick
    question that I’d like to ask if you don’t mind.
    I was curious to know how you center yourself and clear your mind prior to writing.
    I’ve had a difficult time clearing my thoughts in getting my thoughts out.
    I do take pleasure in writing however it just seems like the first 10 to 15 minutes are usually wasted just trying to figure out how to begin. Any suggestions or hints?
    Cheers!

  5. I’ve learn a few excellent stuff here. Definitely worth bookmarking for revisiting.
    I surprise how much effort you put to make the sort of fantastic informative website.

  6. My spouse and I stumbled over here different web page
    and thought I might as well check things out. I like what I see
    so i am just following you. Look forward to going over your web page yet again.

  7. Markdob表示:

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

  8. With havin so much content and articles do you ever
    run into any problems of plagorism or copyright violation? My website has a
    lot of unique content I’ve either written myself or outsourced but
    it looks like a lot of it is popping it up all over the internet without my authorization. Do you know any solutions to help protect against content from being ripped off?
    I’d definitely appreciate it.

  9. BrandenSlomy表示:

    amoxicillin 500mg price in canada: com pharm – buy cheap amoxicillin online

  10. Baby Crib表示:

    What Is The Reason Best Crib Is The Right Choice For You?
    Baby Crib

  11. Dereketerm表示:

    canadian pharmacy amoxicillin: cheap amoxil – where can i get amoxicillin 500 mg

  12. StevenNub表示:

    prednisone 10 mg price: prednisone buy – prednisone 5mg over the counter

  13. BrandenSlomy表示:

    generic amoxicillin cost: Amoxicillin Com Pharm – amoxicillin discount coupon

  14. You’re so interesting! I don’t suppose I have read through a single thing like this before.
    So wonderful to find someone with unique thoughts on this topic.

    Really.. thank you for starting this up. This website is one thing that is required on the internet, someone with a bit of originality!

  15. Uazryjd表示:

    Быстрое обучение и получение диплома магистра – возможно ли это?

    kubiaczyk.com/diplom-o-srednem-tehnicheskom-obrazovanii-kupit.html

  16. Bradleygoath表示:

    cost of prednisone 40 mg raypharm buy prednisone online no prescription

  17. Uazrkrs表示:

    Официальное получение диплома техникума с упрощенным обучением в Москве
    bamcreativestudio.com.au/kupit-attestat-sssr-v-kaliningrade.html

  18. Blakesmema表示:

    купить кухню в екатеринбурге — Легко и удобно приобрести качественную кухню в Екатеринбурге.

  19. Gregg表示:

    This Is The Advanced Guide To Electric Stove Fire electric fire log burner style (Gregg)

  20. StevenNub表示:

    buy amoxicillin 500mg canada: Com Pharm – amoxicillin 500 mg cost

  21. The Butt Plugs Online Store Awards: The Best, Worst,
    And Weirdest Things We’ve Seen butt plugs and Sex
    (http://wownsk-portal.ru/user/bluegoose30)

  22. StevenNub表示:

    max pharm: dapoxetine online – Priligy tablets

  23. 12 Companies Are Leading The Way In Cleveland Mesothelioma Attorney mesothelioma attorneys

  24. StevenNub表示:

    dapoxetine price: priligy – max pharm

  25. Узнай все о варикоцеле диагностика клиника варикоцеле

發佈留言

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