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

  1. Millie Guzman表示:

    After via a travel business enterprise in Atlanta, I’ll in no way plan yet one more trip by myself once more! Their talent is unequalled—observe their offerings at travel agent

  2. Great article. I’m facing a few of these issues as well..

  3. Peter Bowman表示:

    The Hot Springs National Park is a must-visit for anyone seeking to relax in natural thermal waters. To learn more on locations to loosen up in Arkansas, check out https://www.spreaker.com/podcast/albiusjmze–6450395

  4. SamuelBix表示:

    prednisone for sale in canada: PredniBest – prednisone 10 mg price

  5. SamuelBix表示:

    amoxicillin without prescription: amoxicillin 500 mg without prescription – amoxicillin 500mg buy online canada

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

  7. EdgarWat表示:

    Интересные статьи о займах – https://infopro54.ru/news/gde-vzyat-zajm-maksimalno-bystro-i-udobno/

  8. bokep indo表示:

    Hi there colleagues, pleasant piece of writing and pleasant
    urging commented at this place, I am actually enjoying by these.

  9. sga123表示:

    It’s very straightforward to find out any topic on net as compared to books, as I found this article at this website.

  10. Good post but I was wanting to know if you could write a litte more on this topic?
    I’d be very grateful if you could elaborate a little
    bit more. Appreciate it!

  11. National Pub Poker League – 5 New Strategies
    Maintain Your Focus 에볼루션 추천

  12. If you’re feeling overwhelmed after an accident, reach out to a supportive personal injury attorneys near me # who can help lighten the load

  13. You’ll Never Guess This 4 Seater Brown Leather Sofa’s Benefits 4 seater brown leather sofa (http://polimentosroberto.com.br/)

  14. Idesys.co.Kr表示:

    Its like you read my mind! You appear to know
    so much about this, like you wrote the book in it or something.
    I think that you can do with some pics to drive the message home a bit, but
    other than that, this is magnificent blog. An excellent read.
    I’ll definitely be back. http://idesys.co.kr/bbs/board.php?bo_table=free&wr_id=53265

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

  16. Drugs information. Cautions.
    where to get pioglitazone for sale
    Actual information about meds. Get information now.

  17. KennethPah表示:

    buy cipro without rx ciprofloxacin generic п»їcipro generic

  18. RobertJar表示:

    amoxicillin 500 mg without prescription: buy amoxicillin online mexico – buy amoxicillin over the counter uk

  19. Nikefut表示:

    dark web sites links darknet drug market dark net

  20. Hi, Neat post. There is a problem with your site in internet explorer, may check this?
    IE still is the marketplace chief and a good part of other
    folks will miss your wonderful writing due to this problem.

發佈留言

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