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,229,741 Responses

  1. paito hk6表示:

    Link exchange is nothing else except it is just placing the other person’s
    web site link on your page at suitable place and other person will also do same for you.

  2. Hello colleagues, how is everything, and what
    you wish for to say on the topic of this article, in my view its actually amazing for me.

    https://nagasaon4d.my/

  3. Derekfar表示:

    ultrabet yeni giris 1125: ultrabet tr online – ultrabet giris

  4. I got this website from my friend who informed
    me regarding this web page and now this time I am browsing this web site and reading very informative content here.

    https://w2.paitocambodia.club/

  5. Simply desire to say your article is as astounding.
    The clearness to your put up is just great and that i
    could assume you’re an expert in this subject. Fine along with your permission let
    me to clutch your feed to keep up to date with coming
    near near post. Thank you a million and please continue
    the gratifying work.

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

  7. LarryCoell表示:

    en cok kazand?ran slot oyunlar? slot oyunlar? slot oyunlar?

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

  9. Derekfar表示:

    Deneme Bonusu Veren Siteler: Casino Siteleri – Deneme Bonusu Veren Siteler

  10. Your mode of telling the whole thing in this
    piece of writing is actually pleasant, every one can without difficulty know it, Thanks a
    lot.

    https://w2.hongkongpools.one/

  11. History Of Mazda 2 Key Fob: The History Of Mazda 2 Key Fob How much is a new Mazda key fob

  12. ArnHesia表示:

    Checking the price of ivermectin generic cream are much better deals than in local stores.

  13. Hmm it seems like your site ate my first comment (it was extremely long) so I guess I’ll just sum
    it up what I submitted and say, I’m thoroughly enjoying your blog.
    I as well am an aspiring blog writer but I’m still new
    to the whole thing. Do you have any tips for first-time blog writers?
    I’d genuinely appreciate it.

  14. HassanbuifS表示:

    https://slot-tr.online/# slot siteleri
    deneme bonusu veren siteler mycbet.com

  15. The 9 Things Your Parents Teach You About Clearwater Accident Lawyer Accident Lawyer

  16. Best Filter Coffee Machine Tips To Relax Your Daily Lifethe One Best Filter Coffee Machine Technique Every Person Needs To Know Best filter coffee machine

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

  18. Asking questions are in fact pleasant thing if you are not understanding anything totally,
    however this article gives nice understanding yet.

  19. If you want to improve your know-how simply keep visiting this site and be updated with the most recent news posted here.

    https://paitowarnahkangkanet.com/

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

  21. I truly love your blog.. Pleasant colors & theme.

    Did you create this site yourself? Please reply back as
    I’m looking to create my very own website and would love to
    find out where you got this from or what the theme is named.

    Many thanks!

  22. Thank you for every other informative web site. The place else may
    I am getting that type of information written in such an ideal way?
    I’ve a venture that I’m just now working on, and I’ve been on the
    look out for such info.

    https://ww1.datasgp.work/

  23. LarryCoell表示:

    Canl? Casino Siteleri casino siteleri win casino siteleri win

  24. HassanbuifS表示:

    https://matadorbet.bid/# matadorbet bid
    deneme bonusu veren siteler denemebonusu2026.com

  25. Very great post. I simply stumbled upon your weblog and
    wanted to mention that I have truly loved browsing your weblog posts.

    After all I will be subscribing in your feed and I
    am hoping you write again soon!

    http://ww7.livesgp.casa/

  26. brandonraday表示:

    Ваша идея блестяща
    посудите сами: согласно современным данным, 78% граждан штатов живут от зарплаты до зарплаты, среднестатистическая сумма долга американца за обучение в университете составляет приблизительно 30 тысяч «зеленых», Финансовая грамотность а задолженность по кредитным картам америки превышает триллион долларов.

  27. Are Tilt And Turn Windows Any Good Tools To Improve Your Daily Lifethe One Are Tilt And Turn Windows Any Good
    Trick Every Person Should Learn are tilt and turn windows Any good

  28. Derekfar表示:

    matadorbet giris: matadorbet bid – matadorbet bid

發佈留言

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