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,481,636 Responses

  1. Iyannaobesk表示:

    1win poker скачать
    1win poker официальный сайт

  2. Dannyunoto表示:

    Сопровождение мужчин — это особая услуга, которая может включать в себя как деловые, так и личные аспекты.
    В современном мире многие мужчины ищут профессионалов, которые могут помочь им в различных сферах жизни:
    от бизнес-мероприятий до социальных встреч – [url=]снять девушку на час[/url]

  3. Nikefut表示:

    dark web market links dark markets 2024 blackweb official website

  4. Your mode of telling everything in this piece of writing is truly pleasant,
    all be capable of effortlessly be aware of it, Thanks a lot https://chefthierry.ca/menu/

  5. Robertpoure表示:

    Каждая живая елка — это не просто дерево, это хранитель волшебства, который объединяет семьи и друзей в самые светлые моменты жизни. Пусть эта елка станет центром вашего новогоднего праздника, наполненного смехом, счастьем и волшебством!- [url=https://www.vizd.ru/pihta-nordmana-na-novyj-god-dlya-sozdaniya-volshebnogo-prazdnika/]купить пихту Нордмана в СПб[/url]

  6. How Software Program Credit/Debit Card Frauds 다바오 포커 설치방법

  7. Does your website have a contact page? I’m having trouble locating it
    but, I’d like to send you an email. I’ve got some suggestions for your blog you
    might be interested in hearing. Either way, great website and I look forward to seeing
    it expand over time.

  8. SEO Services表示:

    hello there and thank you for your info – I have definitely picked
    up something new from right here. I did however expertise some
    technical issues using this web site, as I experienced to reload the site many times previous to I could get it to load correctly.
    I had been wondering if your hosting is OK? Not that I’m complaining,
    but slow loading instances times will often affect your placement in google and can damage
    your quality score if ads and marketing with Adwords.

    Well I’m adding this RSS to my email and can look out for a lot more of your respective fascinating content.
    Ensure that you update this again very soon.

    my web page; SEO Services

  9. Josephmax表示:

    https://pinup-kazi.kz/# пин ап казино онлайн

  10. After I originally left a comment I appear to have
    clicked on the -Notify me when new comments are added- checkbox and from now on whenever a comment is added I get 4
    emails with the same comment. Perhaps there is a means you are able to remove me from that service?
    Cheers!

  11. Hey there! I could have sworn I’ve been to this blog before but after checking
    through some of the post I realized it’s new to me.
    Anyhow, I’m definitely glad I found it and I’ll be bookmarking and checking back often!

  12. Jamesdiure表示:

    pinup-kazi.kz: пин ап кз – pinup

  13. I highly recommend this service to anyone looking to set up an Ltd company. The process was clear and efficient.

  14. These are truly fantastic ideas in concerning blogging.
    You have touched some good things here. Any way keep up wrinting.

    Also visit my webpage … Alzheimer’s assisted living

  15. DarioTob表示:

    пин ап зеркало: pinup-kazi.ru – пин ап казино официальный сайт

  16. Yes! Finally someone writes about هزینه عمل لیزیک چشم با بیمه تامین اجتماعی.

  17. Nikefut表示:

    dark website dark websites dark net

  18. Jamesdiure表示:

    pinup-kazi.ru: пин ап зеркало – пин ап вход

發佈留言

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