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
I found this very helpful. For additional info, visit physiotherapist parel
Having read this I believed it was extremely informative.
I appreciate you finding the time and effort to put this information together.
I once again find myself spending a significant amount of time both reading and leaving comments.
But so what, it was still worthwhile!
May I simply say what a comfort to uncover an individual who truly understands what
they’re talking about online. You actually know how to
bring an issue to light and make it important. More people have to look
at this and understand this side of the story.
I was surprised that you aren’t more popular since you certainly have the gift.
вывод из запоя цены ростов вывод из запоя цены ростов .
Limos aren’t simply for celebrities anymore! They make every occasion feel unique. Have you tried renting one for a birthday or anniversary? Look into more regarding it at limo
Виртуальный номер телефона даёт возможность подключать любое количество номеров и разговаривать с любого устройства, принимать звонки в офисе или дома купить польский номер телефона
Spot on with this write-up, I honestly think this web site needs
much more attention. I’ll probably be returning to read
more, thanks for the information!
Guide To Accident Claim Lawyers: The Intermediate Guide Towards
Accident Claim Lawyers Accident Claim Lawyer
вывод из запоя цены ростов-на-дону вывод из запоя цены ростов-на-дону .
This was a fantastic resource. Check out salon in kharghar for more
10 Mesothelioma Not Caused By Asbestos Projects Related To
Mesothelioma Not Caused By Asbestos To Extend Your Creativity mesothelioma lawyers; https://ahmad-wong.hubstack.net/this-is-the-complete-listing-of-mesothelioma-asbestos-lawyer-dos-and-donts/,
Wow, marvelous blog layout! How long have you been blogging for?
you make blogging look easy. The overall look of your website is great, let alone
the content!
Thanks for some other great article. The place else may anyone get
that type of info in such an ideal approach of writing? I have a presentation subsequent week,
and I am at the search for such information.
House cleaning services make life so much easier house cleaning near me
sweet bonanza giris: sweet bonanza yorumlar – sweet bonanza
Car Lock Smith: The Good, The Bad, And The Ugly car Lock smith near me
Poker The Review – Check Raising The Devil By Mike
“The Mouth” Matusow 스마트시티 에볼루션
Thank you for sharing your thoughts. I truly appreciate
your efforts and I am waiting for your further post thank you once again.
Guide To Retro Fridge Freezer 50 50: The Intermediate Guide In Retro Fridge Freezer 50 50 retro Fridge Freezer 50 50
Hi there, just wanted to say, I loved this post.
It was inspiring. Keep on posting!
대구에 남성 유흥 주점들만 있는게 아닙니다. 저희 대구호빠도 있습니다.
Great process discussing the resultseasily of nutrients on hair well being! It’s useful how diet plays such a indispensable role. Learn greater at hair stylist
Your ideas on recognizing when to call an emergency situation plumbing technician are so useful– thanks for sharing! top emergency plumbing service
Слушайте, гейы!
Хотите погрузиться в пространство виртуальных-казино и выиграть настоящие средства? Тогда вам к нам! Топ самых лучших игровых сайтов 2025
Наш telegram-аккаунт — ваш гид в пространство лучших виртуальных-игр в Российской Федерации! Мы собрали ТОП-10 надежных игровых сайтов, где вы сможете развлекаться на деньги и вывести свои выигрыши без затруднений.
Что вас поджидает:
Достоверные мнения и рейтинги Рейтинг лучших онлайн-казино от реальных игроков. Отличная репутация всякого площадки подтверждена опытом и клиентами. Неоплачиваемая регистрация и скорый доступ на всех сайтах. Действующие копии для посещения к вашему любимому игровой площадке в каждый время. Мобильная приложение для комфортной развлечения где желаете.
Почему нам?
Безопасные и проверенные игровые площадки с отличными критериями для развлечения. Защита ваших сведений и транзакций гарантирована. Свежие обновления и новости мира онлайн-игр в Российской Федерации.
Just read an article with some fascinating points—sharing it here https://www.fimfiction.net/user/828663/anitatyler
What Is Asbestos Attorneys Georgia And Why Is Everyone Talking About
It? mesothelioma lawyers
Hey there, You’ve done an excellent job. I will certainly
digg it and personally suggest to my friends. I am sure they’ll be benefited from this web site.
Hello there! Would you mind if I share your blog with my myspace group?
There’s a lot of people that I think would really enjoy your content.
Please let me know. Many thanks
https://casinositeleri25.com/# guvenilir casino siteleri
Thank you for the good writeup. It in fact was a amusement account it.
Look advanced to far added agreeable from you! However,
how can we communicate?