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
Hi there, just became aware of your blog through Google, and found that
it is really informative. I am going to watch out for brussels.
I will be grateful if you continue this in future.
Numerous people will be benefited from your writing. Cheers!
https://indiamedfast.shop/# online medicine shopping in india
77 canadian pharmacy
Every weekend i used to pay a quick visit this web page, as i wish for enjoyment, as this this
web page conations in fact nice funny material too.
darknet sites https://github.com/abacuslink4jjku/abacuslink – dark market onion
Mexican Pharm Inter: reliable mexican pharmacies – Mexican Pharm Inter
I visited multiple websites however the audio feature
for audio songs existing at this site is really superb.
visit their website zkLogin
online medicine shopping in india: online medicine shopping in india – online medicine shopping in india
Іt’s the best time to make some ρlans for the futuгe and it is time to
be happʏ. I have read this post and if I could I desirе to ѕjggeѕt you few interesting things
or tips. Perhas you can write next artidⅼes referring tо this article.
I wiszh to гead even more things abokut it!
Herе is my webb site: 1v1lol.me
Hello There. I found your blog using msn. This is an extremely well
written article. I will make sure to bookmark it and come
back to read more of your useful information. Thanks for the post.
I will definitely return.