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
https://canadianpharmacyaapd.shop/# ordering drugs from canada
medicine in mexico pharmacies
Если ты ищешь самые быстрые обновления модов для Android, тогда 5play-mods.ru — твой идеальный выбор! Мы обновляем базу модов практически каждый час, чтобы ты всегда имел доступ к последним версиям. Мгновенные обновления и удобный доступ к новым модам — заходи и не упусти!
India pharmacy ship to USA Best Indian pharmacy Indian Pharmacy Abp
Get the best odds, instant withdrawals & deposits, 24/7 customer service and refer bonus. Enjoy safe and secure betting with Stake786. stake786
AMAZING WORK GUYS JUST KEEP IT UP !
Pin-Up платформасы – Сіздің сенімді ойын әлеміңіз Pin-Up платформасы – бұл тек ойын ғана емес, бұл сенімділік, жылдам төлемдер және керемет тәжірибе. Қазақстанда Pin-Up kz көптеген ойыншылардың жүрегін жаулап алды.
Бұл платформа сізге жоғары сапалы ойын автоматтарын, рулетканы, покерді, бинго және басқа да классикалық және заманауи ойын түрлерін ұсынады. Pin-Up платформасының интерфейсі өте қарапайым және интуитивті.
Негізгі мәзірден сіз ойындар, тіркелу, төлемдер, акциялар және қолдау бөлімдеріне тез қол жеткізе аласыз.
http://oapr.edu.kz/18/?page_id=365&lang=ru
Pin-Up платформасында рулетка, покер, бинго және басқа да көптеген классикалық ойындар бар. Pin-Up казино жоғары сапты провайдерлерден ойындармен жабдықталған, мысалы, Microgaming, NetEnt. Pin-Up платформасында төлемдер әртүрлі әдістермен жүзеге асады: банктік карталар, электронды әмияндар, криптовалюталар. Банктік карталар, Skrill, Neteller және криптовалюталар арқылы төлемдер қолжетімді.
I just could not go away your site prior
to suggesting that I actually loved the standard information an individual supply in your guests?
Is gonna be again frequently in order to check out
new posts
tor drug market https://github.com/darkwebmarketslinks/darkwebmarkets onion dark website
mexican pharmacy acp: mexican pharmacy acp – pharmacies in mexico that ship to usa
mexican pharmacy acp: mexican pharmacy acp – mexican pharmacy acp
Хорошо быть студентом, пока не придет пора писать диплом, что и произошло со мной, но не стоит отчаиваться, ведь есть хорошие компании что помогают с написанием и сдачей диплома на хорошие оценки!
Изначально искал информацию про купить диплом специалиста о высшем образовании, купить диплом ссср в нижнем новгороде, купить диплом ссср московская область, купить левый диплом, куплю диплом рублей, потом попал на diplomybox.com/stati
Medispensary Marijuana Delivery is the the best service providing cannabis at any price and taste read more
https://ameblo.jp/naveridbuy/entry-12861932343.html
Hey I know this is off topic but I was wondering if you
knew of any widgets I could add to my blog that automatically tweet my newest twitter updates.
I’ve been looking for a plug-in like this for quite some time and was hoping
maybe you would have some experience with something like this.
Please let me know if you run into anything. I truly
enjoy reading your blog and I look forward to your
new updates.
There’s definately a lot to learn about this issue. I like
all the points you have made.
Get the best odds, instant withdrawals & deposits, 24/7 customer service and refer bonus. Enjoy safe and secure betting with Stake786. stake 786 com
Great post! We are linking to this great article
on our website. Keep up the good writing.
Vulkan Platinum Casino — это ваш шанс попасть
в мир увлекательных игр и получить незабываемые выигрыши.
Здесь вы найдете разнообразные игры, которые подойдут как для новичков, так
и для опытных игроков. Каждая игра
в нашем казино — это шанс на крупный выигрыш и незабываемые
эмоции.
Что отличает Vulkan Platinum акции и предложения от других казино?
Наши игры лицензированы, а безопасность вашего аккаунта и личных данных всегда на высшем уровне.
Кроме того, для наших игроков
всегда доступны эксклюзивные бонусы
и акции.
Когда начать играть? Присоединяйтесь к Vulkan Platinum и получите
свои первые бонусы и бесплатные вращения
для игры. Вот что вас ждет:
Ежедневные акции, которые помогают увеличить ваши шансы на победу.
Широкий выбор игр с различными тематиками и форматами.
Быстрые и удобные способы пополнения
счета и вывода выигрышей.
Vulkan Platinum — это не просто казино, это ваш шанс
на удачу и крупные выигрыши. https://clubvulkan24-funflicker.world/
darknet market https://github.com/darkwebmarketslinks/darkwebmarkets dark market url
dark markets 2025 https://cannahomedarknetdrugstore.com/ – dark web marketplaces
I know this website gives quality dependent posts and additional information, is there any other site which presents these kinds of information in quality?
mexico drug stores pharmacies: mexican pharmacy acp – mexican pharmacy acp
Hemp Seed Oil Combo: Rich formulated full spectrum CBD crafted with hemp seed
oil and cannabidiol. However, Highland Pharms CBD Hemp Oil products receive only Full Spectrum CBD
Extract. Went to meet my boyfriend’s parents for
the first time the other day and took a dropper full
of the 500mg peppermint oil. If your order is placed
after this cut-off, your order will be shipped
the next day. I have been taking this CBD oil in the mornings right after I wake up
and it’s given me a nice emotional boost to start the day.
I have tried a lot of CBD brands and nothing calms me
as this CBD oil does. Shop products from small business brands
sold in Amazon’s store. If you want the goodness of organic coconut MCT oil (carrier oil) and hemp oil,
you should order from CBDFx which is one of the best brands on the
market right now. Our topical CBD cream is formulated
with several deeply nourishing plant-based skin nutrients – like Happy Hemp CBD Reviews oil,
shea butter and jojoba seed oil – to help relieve dry skin, plus a blend of nutrient-rich plant botanicals to support the appearance
and feel of smooth, healthy skin.
Hello my family member! I want to say that this article
is amazing, nice written and include approximately all vital infos.
I would like to peer more posts like this .
Hi there, this weekend is nice designed for me, for the reason that this time i
am reading this enormous educational piece of writing here at my house.
500 000 тенге для пластиковых карт.
Visit my web page: https://cryptobosscasino.art/
My family members all the time say that I am killing my time here at net,
except I know I am getting knowledge every day by reading thes
good articles or reviews.
mexican drugstore online: mexican rx online – mexican pharmacy acp
dark web markets https://kingdom-darkmarketplace.com – dark web drug marketplace
Nice weblog here! Additionally your website loads up very fast!
What host are you the usage of? Can I get your associate link to your host?
I desire my web site loaded up as quickly as yours lol