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,231,345 Responses

  1. Hi there, this weekend is good in support of me, as this occasion i am reading this fantastic informative
    article here at my residence.

  2. Stephenideox表示:

    Погрузитесь в течение юдоль скорби развлечений также увлекательных ситуаций на портале Любовь 28!
    любовь

  3. How To Beat Your Boss In Bean To Cup Coffe Machine bean to cup coffee machine home

  4. wonderful points altogether, you just gained a new
    reader. What may you suggest about your put up that you just made
    a few days ago? Any positive?

    https://ww1.prediksioni.sbs/

  5. Derekfar表示:

    deneme bonusu veren siteler betturkey betturkey.com: deneme bonusu veren siteler mycbet.com – deneme bonusu veren siteler yerliarama.org

  6. fuck at mall表示:

    Hello it’s me, I am also visiting this web site daily, this web site is
    really pleasant and the people are truly sharing fastidious thoughts.

  7. Why You’ll Want To Read More About Mobility Scooter For
    Seniors Adjustable mobility Scooters

  8. 10 Misconceptions Your Boss Has Regarding Seat Leon Key Fob Replacement Seat mii replacement key

  9. Derekfar表示:

    slot tr online: slot siteleri – az parayla cok kazandiran slot oyunlar?

  10. Diplomi_wcMl表示:

    купить аттестат за 11 класс в нижнем новгороде many-diplom77.ru .

  11. Тут можно преобрести несгораемый сейф цена огнестойкие сейфы

  12. The Best Bunk Beds For Adults Tricks To Transform Your Life best Bunk beds

  13. Sazrzqb表示:

    Приобретение диплома ПТУ с сокращенной программой обучения в Москве

    lightsdemons.phorum.pl/viewtopic.php?p=68957#68957

  14. The Most Convincing Proof That You Need Sports Toto
    토토사이트

  15. Тут можно преобрести оружейный шкаф цена шкаф для оружия купить

  16. Are You Responsible For An Toto Rules Budget?
    12 Best Ways To Spend Your Money 메이저사이트 바록가기

  17. The 10 Most Scariest Things About L Shaped Leather Settee l shaped Leather Settee

  18. Diplomi_zvMl表示:

    купить диплом спбгу many-diplom77.ru .

  19. Greetings from Idaho! I’m bored at work so I decided to browse
    your site on my iphone during lunch break. I enjoy
    the info you provide here and can’t wait to take a look when I get home.
    I’m shocked at how quick your blog loaded on my mobile
    .. I’m not even using WIFI, just 3G .. Anyways,
    excellent blog!

  20. Тут можно преобрести сейф пожаростойкий сейфы пожаростойкие

  21. I visited several websites however the audio quality for audio songs present at this web site is in fact
    superb.

    http://w1.seringjitu.cfd/

  22. audi Car keys表示:

    5 Laws That Anyone Working In Audi A3 Key Battery Should Know
    audi Car keys

  23. CarrollUnton表示:

    deneme bonusu veren siteler yeni https://matadorbet.bid/# matadorbet.bid

  24. The Most Significant Issue With Fireplace On Wall, And How You
    Can Fix It White Fireplace

  25. LarryCoell表示:

    ultrabet giris ultrabet ultrabet bonus

  26. www.google.mn表示:

    15 Reasons To Love Virtual Mystery Boxes Mystery box opening, http://www.google.mn,

發佈留言

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