数组去重
Posted tong24
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了数组去重相关的知识,希望对你有一定的参考价值。
题目:
【JS排序】
var str = "1245242"; //这是数组
要求从出现次数多到少排序
示例结果:2:3,4:2,1:1,5:1
【2出现3次,4出现2次...】
答案:
// 1
var arr = [1,2,3,4,4,5,6,7,8,8,8,9,0];
function unique(arr) {
var tmp = new Array();
for (var i in arr) {
if (tmp.indexOf(arr[i]) == -1) {
tmp.push(arr[i]);
}
}
return tmp;
console.log(tmp);
}
// 2
var str = ‘1245242‘;
var array = str.split(‘‘);
var filter = [];
var result = [];
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();
for(index in result){
var show = result[index].split(‘:‘);
document.write(index==0?show[1]+‘出现‘+show[0]+‘次‘:‘,‘+show[1]+‘出现‘+show[0]+‘次‘);
}
// 3
Array.prototype.unique = function () {
var newArr = [this[0]];
for (var i = 0, len = this.length; i < len; i++) {
var repeat = false;
for (var j = 0, len2 = newArr.length; j < len2; j++) {
if (this[i] == newArr[j]) {
repeat = true;
break;
}
}
if (!repeat) {
newArr.push(this[i]);
}
}
return newArr;
};
var arr = [1,2,3,4,5,6,7,1,2,3,4];
alert(arr.unique(arr));
// 4
Array.prototype.unique2 = function(argument) {
this.sort();
var newArr = [this[0]];
for (var i = 0, len2 = this.length; i < len2; i++) {
if (this[i] !== newArr[newArr.length - 1]) {
newArr.push(this[i]);
}
}
return newArr;
};
var array2 = [‘b‘, ‘b‘, ‘v‘, ‘n‘];
alert(array2.unique2());
// 5
Array.prototype.unique3 = function () {
var res = [];
var json = {};
for (var i = 0; i < this.length; i++) {
if (!json[this[i]]) {
res.push(this[i]);
json[this[i]] = 1;
}
}
return res;
}
var array3 = [‘b‘, ‘b‘, ‘v‘, ‘n‘];
alert(array3.unique3());
以上是关于数组去重的主要内容,如果未能解决你的问题,请参考以下文章