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’m impressed, I must say. Seldom do I come across a blog that’s both
educative and amusing, and without a doubt, you’ve hit the nail on the head.
The problem is an issue that not enough people are speaking intelligently
about. I am very happy that I came across this during my hunt for something regarding
this.
Идеальный букет невесты для вашей свадьбы, для незабываемого образа на свадьбе.
Шаг за шагом: соберите уникальный букет невесты, для особенного момента.
Лучшие тренды в букете невесты, для свадебной церемонии.
Как сэкономить на букете невесты без потери красоты, для экономии на свадьбе.
Реальный или искусственный букет невесты: преимущества и недостатки, чтобы было меньше забот и больше радости.
Букет невесты в стиле минимализм, для современной невесты.
Стильные сочетания букета и платья невесты, для незабываемых фотосессий.
заказать букет невесты нижний новгород https://buketnevestynn.ru/ .
pinup kazi: пин ап казино – пин ап зеркало
Nightlife 하이오피사이트
Your mode of telling the whole thing in this paragraph is really nice, every one can without difficulty be aware of it, Thanks a lot https://www.cliniquedelenfant.ca/le-developpement-psycho-affectif-des-enfants-et-la-facon-de-le-developper/
vavada: казино вавада – vavada
Можно ли купить аттестат о среднем образовании, основные моменты и вопросы
If you want to improve your knowledge only
keep visiting this site and be updated with the hottest news update posted here.
Thanks for the marvelous posting! I definitely enjoyed reading it, you will be a great author.I will remember to
bookmark your blog and definitely will come back very soon.
I want to encourage you continue your great posts, have a nice weekend!
Terminated Reading a Blog Post: A Formal Reply
to the Comment Section and an Invitation to Join “KING855”
‘After diligently examining the blog post, I would like to present the following commentary to the
comment .
Your perspectives on the theme were quite intellectually stimulating
. I found myself in agreement with many of the assertions
you brought up .
It is gratifying to see such an animated dialogue taking place .
If you are interested in additional delving into this topic ,
I would warmly encourage you to participate in the “KING855” platform.
In that space, you will have the chance to interact with kindred spirit participants and explore
further into these fascinating subjects.
I am confident your contribution would be a significant
enrichment to the discussion .
Appreciate your contribution , and I anticipate the prospect of extending
this stimulating conversation.
Here is my web page – lottery
pinup: pinup kazi – pinup kazi
Relaxation Therapy 하이오피주소
пинап казино: pinup-kazi.ru – пин ап казино официальный сайт
Thank you for the auspicious writeup. It
best realtor in ponce inlet fl fact was a amusement account it.
Look advanced to more added agreeable from you!
However, how could we communicate?
Сколько стоит диплом высшего и среднего образования и как это происходит?
Very quickly this site will be famous amid all blogging and site-building visitors, due to it’s
nice articles
Пошаговая инструкция по безопасной покупке диплома о высшем образовании
pinup: pinup-kazi.ru – пинап казино
Предлагаем услуги профессиональных инженеров офицальной мастерской.
Еслли вы искали сервисный центр huawei в москве, можете посмотреть на сайте: сервисный центр huawei в москве
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
пин ап кз: пинап казино – пин ап казино онлайн
vavada kazi: vavada kazi – vavada
пин ап казино онлайн pin up казино пин ап казино онлайн
Предлагаем услуги профессиональных инженеров офицальной мастерской.
Еслли вы искали сервисный центр huawei в москве, можете посмотреть на сайте: официальный сервисный центр huawei
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
Как официально купить аттестат 11 класса с упрощенным обучением в Москве
vavada kazi: vavada – vavada
пин ап зеркало: пин ап казино официальный сайт – pinup-kazi.ru
pin up казино: pinup – pin up казино
Drugs information leaflet. What side effects?
can i buy generic phenytoin
Some trends of medicines. Read information now.
вывод из запоя воронеж https://www.spilkuvannya.rolevaya.com/viewtopic.php?id=68 .
Сколько стоит диплом высшего и среднего образования и как это происходит?