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,232,495 Responses

  1. 14 Misconceptions Commonly Held About Window
    Repairs Near Me Upvc window Repairs near me

  2. qooh.me表示:

    You’ll Be Unable To Guess Upvc Window Repairs Near Me’s Secrets upvc window repair –
    qooh.me,

  3. 10 Facts About Upvc Window Repairs That Will Instantly Put You In A Positive Mood Window Repairs Near Me

  4. Why Personal Injury Lawyers Is Everywhere This Year Lander personal injury lawsuit

  5. see this表示:

    Simply desire to say your article is as astounding. The clarity in your post is just great and i could assume you’re an expert on this subject. Fine with your permission let me to grab your RSS feed to keep updated with forthcoming post. Thanks a million and please keep up the rewarding work.

  6. bandar togel表示:

    Hey very nice blog!

  7. JamesNow表示:

    Buy generic Levitra online: Levitra generic price – Levitra price

  8. EsenistrGed表示:

    Циклёвка паркета: особенности и этапы услуги
    Циклёвка паркета — это процесс восстановления внешнего вида паркетного пола путём удаления верхнего повреждённого слоя и возвращения ему первоначального вида. Услуга включает в себя несколько этапов:
    Подготовка: перед началом работы необходимо защитить мебель и другие предметы от пыли и грязи, а также удалить плинтусы.
    Шлифовка: с помощью шлифовальной машины удаляется старый лак и верхний повреждённый слой древесины.
    Шпатлёвка: после шлифовки поверхность паркета шпатлюется для заполнения трещин и выравнивания поверхности.
    Грунтовка: перед нанесением лака паркет грунтуется для улучшения адгезии и защиты от плесени и грибка.
    Нанесение лака: лак наносится в несколько слоёв с промежуточной шлифовкой между ними.
    Полировка: после нанесения последнего слоя лака паркет полируется для придания поверхности блеска и гладкости.
    Циклёвка паркета позволяет обновить внешний вид пола, восстановить его структуру и продлить срок службы.
    Сайт: ykladka-parketa.ru Циклёвка паркета

  9. ElmerWes表示:

    Cenforce 100mg tablets for sale cheapest cenforce Cenforce 100mg tablets for sale

  10. What Freud Can Teach Us About Bean To Cup Coffee Machine easy To Clean Coffee machines

  11. The Reasons Windows Repairs In 2023 Is The Main Focus Of All People’s Attention. 2023 upvc door repairs near me

  12. Xavier表示:

    Upvc Windows Near Me Tools To Streamline Your Daily
    Lifethe One Upvc Windows Near Me Trick That Should Be Used By Everyone Know upvc windows
    near me, Xavier,

  13. Guide To Kayleigh Pornstar: The Intermediate Guide To Kayleigh Pornstar Kayleigh pornstar

  14. Door Fitters Leeds The Process Isn’t As Hard As You Think conservatory door repairs leeds

  15. Mack表示:

    Five Killer Quora Answers To Butt Plugs Store app controlled
    buttplug – Mack

  16. DavidOwelo表示:

    http://cenforce.pro/# cenforce for sale

  17. ElmerWes表示:

    Cheap Levitra online levitrav.store Buy Vardenafil 20mg online

  18. You’ll Never Guess This Mini Cooper Car Key Replacement’s Tricks Mini Cooper car key Replacement

  19. Unquestionably imagine that that you stated. Your favorite reason appeared
    to be at the internet the simplest factor to have
    in mind of. I say to you, I definitely get irked while other people think about
    concerns that they just do not recognise about. You
    managed to hit the nail upon the top as well as defined out the
    whole thing without having side-effects , folks could take a signal.

    Will probably be again to get more. Thank you

  20. Wildfire Case表示:

    10 No-Fuss Ways To Figuring Out The CSGO Most Profitable Cases In Your Body.

    Wildfire Case

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

  22. 10 Replacement Upvc Window Handles Tricks All Experts Recommend Upvc window repair near me

  23. 10 Misconceptions That Your Boss May Have About Foldaway Treadmill With Incline
    Foldaway Treadmill With Incline Why Is Incline Treadmill Good

  24. window doctor表示:

    Why People Don’t Care About Repair Double Glazing Windows window doctor

  25. upvc表示:

    A Cheat Sheet For The Ultimate On Double Glazed Window
    Repairs upvc

  26. The 9 Things Your Parents Teach You About Walking Pad For Desk walking pad for desk

  27. GeorgeSep表示:

    cheapest cenforce: order cenforce – Cenforce 150 mg online

  28. CharlesDog表示:

    http://viagras.online/# Buy Viagra online cheap

  29. WillieRully表示:

    We bieden tijdelijke telefoonnummers in tientallen landen over de hele wereld, met duizenden nummers om uit te kiezen https://beauanwi93692.weblogco.com/26851381/het-belang-van-tijdelijke-mobiele-nummers-een-grondige-verkenning

  30. JamesNow表示:

    Kamagra Oral Jelly: kamagra pills – buy kamagra online usa

發佈留言

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