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,227,690 Responses

  1. The Eater Chicago article dives into “Mom’s Chicago,” a distinctive pop-up by Konbini &
    Kanpai that offers Japanese-American yoshoku cuisine to the city.

    This pop-up blends traditional Japanese flavors with American ingredients, creating a fusion of
    comfort food that is both innovative and flavorful. The concept intends to display the versatility of yoshoku dishes, presenting a new dining experience for Chicagoans.
    For more insight, check out the full article on Eater Chicago.

  2. Darrelherse表示:

    deneme bonusu veren siteler: slot siteleri guvenilir – slot oyun siteleri

  3. Darrelherse表示:

    deneme bonusu veren slot siteleri: slot siteleri 2024 – 2024 en iyi slot siteleri

  4. Darrelherse表示:

    deneme bonusu veren slot siteleri: oyun siteleri slot – 2024 en iyi slot siteleri

  5. Link exchange is nothing else except it is simply placing the other person’s
    website link on your page at proper place and other person will also do same in support of you.

  6. I am no longer certain the place you are getting your
    information, but great topic. I must spend some time studying much more
    or working out more. Thank you for excellent info I used to be looking for this info for my mission.

  7. Kennethmab表示:

    Официальный клуб Sukaaa предлагает новым игрокам бонус 325% на депозит, за активное повышение аккаунта – игрок получает кэшбэк и быстрые выводы. Новых пользователей привлекает не только бонус бездеп за регистрацию, но и дизайн https://t.me/s/sykaaa_official_casino на сайте наглядное меню, которое позволяет в пару кликов найти нужный софт, выбрать игровой автомат или сделать депозит.

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

  9. KevinSounc表示:

    http://sweetbonanza.network/# sweet bonanza

  10. Hello! I know this is kinda off topic however , I’d figured I’d ask.

    Would you be interested in trading links or maybe guest
    authoring a blog article or vice-versa? My website goes over a lot of the same topics as yours and I think we could greatly
    benefit from each other. If you’re interested feel free to send me an e-mail.

    I look forward to hearing from you! Awesome blog by the way!

  11. Thank you for the good writeup. It in fact was a amusement
    account it. Look advanced to far added agreeable from you!
    By the way, how could we communicate?

  12. Five Killer Quora Answers On Skoda Car Key Replacement Cost
    skoda Car key Replacement

  13. Darrelherse表示:

    en iyi slot siteleri 2024: en yeni slot siteleri – slot kumar siteleri

  14. I’m no longer sure where you’re getting your info, however great
    topic. I needs to spend some time learning much more or understanding more.

    Thanks for excellent information I was looking for this info for my mission.

  15. child porn表示:

    If you wish for to take a good deal from this article
    then you have to apply these strategies to your won web site.

  16. Darrelherse表示:

    deneme bonusu veren slot siteleri: casino slot siteleri – deneme bonusu veren siteler

  17. ev taşıma表示:

    Evden Eve Nakliyat | Ev taşıma sırasında dikkat edilmesi gerekenler konusunda verdiğiniz bilgiler çok değerli. Kozcuoğlu Evden Eve Nakliyat olarak, müşterilerimize en güvenilir hizmeti sunmaya devam ediyoruz.

  18. Colette表示:

    10 Websites To Help You To Become An Expert
    In Mobility Scooters For Sale Second Hand cheap electric mobility scooters for sale (Colette)

  19. Darrelherse表示:

    en iyi slot siteleri: slot kumar siteleri – en guvenilir slot siteleri

  20. Darrelherse表示:

    deneme veren slot siteleri: slot siteleri 2024 – slot siteleri

  21. I love your blog.. very nice colors & theme. Did you
    create this website yourself or did you hire someone to do
    it for you? Plz respond as I’m looking to create my own blog
    and would like to know where u got this from. cheers

  22. I’m g᧐ne to say t᧐ my little brother, that he shоuld alsⲟ ppay a visit
    thіs weblog on regular basis t᧐ get updated frоm
    latest gossip.

    Also visit mmy ρage; PokemonToto Live Chat

發佈留言

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