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,675 Responses

  1. Sazrmtd表示:

    Можно ли купить аттестат о среднем образовании? Основные рекомендации
    netcs.ru/forum/member.php?u=4834

  2. 15 Reasons You Shouldn’t Be Ignoring Cheap Butt Plugs how to make A butt sex toy

  3. Very good information, Appreciate it.

  4. CarrollUnton表示:

    deneme bonusu veren siteler 2024 http://ultrabet-tr.online/# ultrabet tr online

  5. Why You’ll Need To Find Out More About Three Wheel Mobility Scooters Sale local mobility scooters For sale

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

  7. 20 Important Questions To To Ask About Wall Mount Fireplace Before You Decide To Purchase It Wall Mounted Fire
    (https://Www.Indiegogo.Com)

  8. Unquestionably believe that which you stated.
    Your favorite reason appeared to be on the net the simplest thing to be aware of.
    I say to you, I definitely get annoyed while people think about worries that
    they just do not know about. You managed to hit the nail upon the top and also defined
    out the whole thing without having side-effects , people can take a signal.
    Will probably be back to get more. Thanks

  9. JohnnyTex表示:

    Веб агентство в Москве выполняет разработку сайтов на платформе Битрикс под ключ. Дополнительные услуги – продвижение в поисковых системах Яндекс и Гугл, техническая поддержка, обслуживание, аудит, тестирование, наполнение контентом, контекстная реклама и маркетинг webstudiya razrabotki ru

  10. Sazruck表示:

    Как оказалось, купить диплом кандидата наук не так уж и сложно

    tr.clanfm.ru/posting.php?mode=post&f=33&sid=39a29064d0bed44eb75f216fb53a1986

  11. Nicholas表示:

    10 Things That Your Family Taught You About Couches Sale couches sale (Nicholas)

  12. Manuelrof表示:

    Melbet – начинай играть на реальные деньги на официальном сайте онлайн казино Мелбет и выигрывай крупные суммы в популярных игровых автоматах kometa зеркало kometacasino74 online

  13. LarryCoell表示:

    matadorbet matadorbet matadorbet.bid

  14. What Is Lightweight 3 Wheel Electric Scooter? To Utilize It Scooter 3 Wheeler

  15. Thank you for every other fantastic article. Where
    else could anyone get that type of info in such an ideal method of
    writing? I have a presentation next week, and I am at the look for such info.

  16. купить дермантин для обивки стульев http://iskusstvennaya-kozha-dlya-mebeli-kupit.ru/ .

  17. This Week’s Top Stories About Velvet Chesterfield
    Sofa chesterfield sofas near me

  18. Why No One Cares About Replacement Audi Key audi key Programmer

  19. купить дермантин для обивки стульев https://www.iskusstvennaya-kozha-dlya-mebeli-kupit.ru .

  20. https://watchnow.gomuviz.com/

    I do not even know how I ended up here, but I thought this post was good.
    I do not know who you are but definitely you’re going to a famous blogger if
    you are not already 😉 Cheers!

  21. Sazrrux表示:

    Аттестат школы купить официально с упрощенным обучением в Москве

    ilk-nachalo.ru/blog.php?u=1670&b=924

  22. What Freud Can Teach Us About Sports Toto 안전놀이터 순위

  23. Wonderful, what a blog it is! This blog provides helpful data to us, keep it up.

  24. Your Family Will Be Thankful For Getting This Glass Repairs Windows Stained Glass Repair Near Me

  25. CarrollUnton表示:

    denemebonusuverensiteler.top https://ultrabet-tr.online/# ultrabet

發佈留言

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