个人总结的三种过滤重复的数组的方法
方法1:
<script>
function unique(target) {
var result = [];
loop:
for (var i = 0, n = target.length; i < n; i++){
for (var x = i + 1; x < n; x++) {
if (target[x] === target[i])
continue loop;
}
result.push(target[i]);
}
return result;
}
var arr = ['a','b','b','c',1,2,2,3]
alert(unique(arr)); //a,b,c,1,2,3
</script>
方法2:
<script>
Array.prototype.distinct = function () {
var newArr = [],obj = {};
for(var i=0, len = this.length; i < len; i++){
if(!obj[typeof(this[i]) + this[i]]){
newArr.push(this[i]);
obj[typeof(this[i]) + this[i]] = 'new';
}
}
return newArr;
}
var arr =['a','b','b','c'];
alert(arr.distinct());
</script>
方法3:
<script>
Array.prototype.distinct = function () {
var sameObj = function(a, b){
var tag = true;
if(!a || !b) return false;
for(var x in a){
if(!b[x]) return false;
if(typeof(a[x]) === 'object'){
tag = sameObj(a[x],b[x]);
} else {
if(a[x]!==b[x])
return false;
}
}
return tag;
}
var newArr = [], obj = {};
for(var i = 0, len = this.length; i < len; i++){
if(!sameObj(obj[typeof(this[i]) + this[i]], this[i])){
newArr.push(this[i]);
obj[typeof(this[i]) + this[i]] = this[i];
}
}
return newArr;
}
//一维数组
var arr =['a','b','b','c'];
alert(arr.distinct());
//关联数组
var arr=[{name:"tom",age:12},{name:"lily",age:22},{name:"lilei",age:12}];
var newArr=arr.distinct(function(ele){
return ele.age;
});
alert('重复项:'+newArr[0]['age'])
</script>