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
Kamagra Oral Jelly Sildenafil Oral Jelly sildenafil oral jelly 100mg kamagra
Greetings! This is my first visit to your blog! We are a collection of volunteers and starting a new initiative in a
community in the same niche. Your blog provided us useful information to work on. You have done a wonderful job!
my web-site: Prompt Scripting
http://kamagraiq.com/# Kamagra Oral Jelly
นักเดิมพันคนใดที่อยากแนะนําเว็บสล็อต แตกง่าย 2024มีบริการที่ครบบริบรูณ์ จำต้องเว็บแห่งนี้เว็บไซต์เดียวเพียงแค่นั้นสล็อตเว็บใหญ่อันดับ 1ถูกตามกฎหมายและก็ตามมาตรฐานใหม่ล่าสุด พร้อมมอบประสบการณ์ที่น่าระทึกใจให้กับทุกคน และยังมีการระบบฝากถอนเงินที่เร็วทันใจ
of course like your website but you need to test the spelling on quite a few of your posts.
A number of them are rife with spelling problems and I to find it very bothersome to inform the reality however I will
certainly come again again.
My homepage … Cloud Platforms
Viagra tablet online buy viagra online buy Viagra over the counter
Write more, thats all I have to say. Literally, it seems as though you relied on the video to make your point.
You clearly know what youre talking about, why throw away
your intelligence on just posting videos to your site when you could be giving us something informative to read?
My web blog :: Recensioner
Hello! Quick question that’s completely off topic.
Do you know how to make your site mobile friendly?
My weblog looks weird when browsing from my iphone.
I’m trying to find a template or plugin that might be
able to fix this problem. If you have any suggestions, please share.
Appreciate it!
Feel free to surf to my homepage – Omdömen
Sildenafil Citrate Tablets 100mg: cheapest viagra – sildenafil over the counter
Buy Tadalafil 5mg: Generic Tadalafil 20mg price – Cheap Cialis
I’m pretty pleased to uncover this web site. I want to to thank you for ones time for this fantastic read!!
I definitely appreciated every bit of it and i also have you saved to fav to check out new stuff in your web site.
my blog gpt prompts
http://kamagraiq.com/# super kamagra
https://samara-benefis.ru/
9 Signs You’re A Car Accident Attorneys Expert attorneys
I love it when people get together and share thoughts.
Great site, keep it up!
Viagra without a doctor prescription Canada: sildenafil iq – sildenafil 50 mg price
I am really inspired together with your writing talents as smartly as
with the format in your blog. Is that this a paid theme or
did you modify it your self? Either way stay
up the nice quality writing, it’s rare to peer a nice weblog like
this one today..
Tadalafil price cheapest cialis Tadalafil Tablet
http://sildenafiliq.xyz/# buy viagra here
http://tadalafiliq.shop/# Buy Tadalafil 10mg
http://sildenafiliq.xyz/# order viagra
Greetings! I know this is somewhat off topic but I was
wondering if you knew where I could locate a captcha plugin for my comment form?
I’m using the same blog platform as yours and I’m having trouble finding one?
Thanks a lot!
Hey there! I just wish to offer you a huge thumbs up for the excellent info you’ve got here on this post.
I’ll be returning to your web site for more soon.
We’re a group of volunteers and opening a new scheme in our community.
Your website offered us with valuable information to work on. You have done a formidable job and our
whole community will be grateful to you.
Your method of telling the whole thing in this post is
actually nice, all be able to simply understand it, Thanks a lot https://www.entreprisesrealberube.ca/cablage-electrique-d-une-maison/
https://youdip.ru
So , You’ve Purchased Loft Beds For Kids … Now What? Loft Bed
With Desk Underneath (Mariskamast.Net)
Что не так с инвестиционной компанией Life is Good — пирамида или нет?
анальный секс смотреть
Инвестпривет, друзья! Подписчица Марина спросила меня о том, что я думаю об инвестиционной компании Life is Good, а также об инвестиционном счете Vista. Первый взгляд на Life is Good убедил меня, что ничего хорошего из инвестиций в нее не выйдет. Второй взгляд – тоже. И вот почему. И да, демотиваторов здесь не будет. И без них смешно.
Сайт сделан на коленке
Если зайти на официальный сайт, то тут тихий ужас. Синий фон, звезды, отсутствие адаптивной верстки (особенно на мобильных устройствах сайт смотрится ужасно, попробуйте сами зайти) – а-ля привет из 90-х. Ребята, так уже даже в нулевые не делали. А на дворе – 2019-й, скоро 20-е годы XXI века начнутся. Вы опоздали с дизайном лет так на 30.
Далее. Сразу же справа вываливается форма, предлагающая начинать онлайн-чат с оператором. На полстраницы, перекрывая весь контент. Это сайт международной организации? Серьезно?
Далее смотрим, что сайт доступен аж на 9 языках! Захожу в английскую версию, ибо другими языками не владею. И что я вижу? Грубые грамматические и орфографические ошибки на уровне 7 класса средней школы. На скрине выделил лишь наиболее бросающиеся в глаза. Но одна фразочка «who specializiruetsya» уже доставляет.
Смысловое содержание сайта
Ну ладно. Чего я к дизайну-то привязался? У Нью-Йоркской биржи сайт тоже не фонтан. Может, недостатки дизайна компенсирует полезная инфа?
И тут облом. В разделе «О компании» я ожидаю увидеть какие-то данные – кто основал контору, кто является бенифициаром, кто инвесторы, сколько офисов, сотрудников, куда именно инвестирует Life is Good, какая прибыль, убытки. Но ничего этого нет. Просто несколько мотивационных фраз в духе: «Хватит работать на дядю, нести деньги нам и начинай чувствовать себя финансово независимым». Ну и несколько очевидно проплаченных роликов, залитых на Youtube.
Почему международная корпорация поскупилась на аренду или покупку собственного сервера, чтобы размещать там видео – загадка.
I have read so many articles concerning the blogger lovers except this post is actually a pleasant post, keep it up.