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,370,380 Responses

  1. You can’t underestimate the power of good SEO in attracting clients as a lawyer. Check out seo marketing for lawyers for valuable advice

  2. Myrtie Ellis表示:

    Clearly laid out steps regarding maintaining an active seo for legal firm

  3. Beatrice Nash表示:

    Excited to learn more about eco-friendly roofing options—it’s about time we start considering the planet too! shingle roofers

  4. Lillie Moody表示:

    I appreciate that metal roofs can be applied over existing shingles, saving time and money! Find out how at roofers

  5. Pearl Mathis表示:

    Excellent advice about optimizing your practice’s online presence; definitely seeking out a skilled # attorney seo companies #

  6. George Tucker表示:

    The installation time for a metal roof seems much quicker than traditional options—great for busy homeowners! More insights at residential roofing company

  7. Pills information sheet. What side effects?
    doxycycline hyc 100mg via feeding tube
    All about medicine. Get information here.

  8. Nikefut表示:

    darknet websites dark market https://darknetmarketstore.com/ – dark web access

  9. Hester Hodges表示:

    Building a strong online reputation is critical for lawyers today; check out ideas from seo for lawyers

  10. Love this perspective on lawyer marketing attorney seo companies

  11. Thanks very nice blog!

  12. Brandon Ford表示:

    I’m planning to install solar panels roofing contractors vancouver

  13. finance表示:

    Great blog you have here but I was curious about if you knew of any message boards that cover the same topics
    talked about here? I’d really love to be a part of community where I can get opinions from other experienced
    people that share the same interest. If you have any recommendations, please let me know.
    Bless you!

  14. Definitely consider that that you said. Your favorite reason seemed
    to be on the internet the simplest thing to take note
    of. I say to you, I certainly get annoyed whilst people think about
    issues that they plainly don’t recognize about. You controlled
    to hit the nail upon the top as neatly as
    defined out the whole thing without having side-effects , other people could
    take a signal. Will probably be back to get more. Thanks

  15. Outstanding story there. What happened after?
    Good luck!

  16. bokep terbaik sma toket gede menyala banget

  17. This is very insightful. Check out roof repair san antonio for more

  18. Markdob表示:

    Всем привет! Может кто знает, где почитатьразные блоги о недвижимости? Сейчас читаю – https://keskps.ru

  19. pin up casino表示:

    Игроки автоматически перенаправляются на действующее зеркало.

  20. Markdob表示:

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

  21. TimothyNib表示:

    Удерживает популярные общественные стульчик: Facebook, VK, Instagram, Одноклассники также т.д. Чечен Заменяет тг улучит по фото через мала до велика инфу что касается народе!
    официальный глаз бога Два хунта а также Глаз Создателя найдет все данные относительный авто. База сверху десятки миллионов из открытых источников.

  22. Sweet blog! I found it while browsing on Yahoo
    News. Do you have any suggestions on how to get listed in Yahoo News?
    I’ve been trying for a while but I never seem to
    get there! Appreciate it

發佈留言

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