1: 借助新数组 判断新数组中是否存在该元素如果不存在则将此元素添加到新数组中
var arr = [1,23,1,1,1,3,23,5,6,7,9,9,8,5];
Array.prototype.reArr = function(){
var newArr = [];
for(var i = 0; i < this.length; i++){
if(newArr.indexOf(this[i])== -1){
newArr.push(this[i]);
}
}
return newArr;
}
var arr2 = arr.reArr();
console.log(arr); //[ 1, 23, 1, 1, 1, 3, 23, 5, 6, 7, 9, 9, 8, 5 ]
console.log(arr2);//[ 1, 23, 3, 5, 6, 7, 9, 8 ]
for循环也可以替换为orEach
Array.prototype.distinct = function (){
var arr = this,
result = [],
len = arr.length;
arr.forEach(function(v, i ,arr){ //这里利用map,filter方法也可以实现
var bool = arr.indexOf(v,i+1); //从传入参数的下一个索引值开始寻找是否存在重复
if(bool === -1){
result.push(v);
}
})
return result;
};
var a = [1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3,3,2,3,3,2,2,1,23,1,23,2,3,2,3,2,3];
var b = a.distinct();
console.log(b.toString()); //1,23,2,3
2: 数组递归去重
rray.prototype.distinct = function (){
var arr = this,
len = arr.length;
arr.sort(function(a,b){ //对数组进行排序才能方便比较
return a - b;
})
function loop(index){
if(index >= 1){
if(arr[index] === arr[index-1]){
arr.splice(index,1);
}
loop(index - 1); //递归loop函数进行去重
}
}
loop(len-1);
return arr;
};
var a = [1,2,3,4,5,6,5,3,2,4,56,4,1,2,1,1,1,1,1,1,56,45,56];
var b = a.distinct();
console.log(b.toString()); //1,2,3,4,5,6,45,56
3: es6 方法
let array = Array.from(new Set([1, 1, 1, 2, 3, 2, 4]));
注释:此方法有兼容性问题
只检测是否重复
var s = [2, 3,2, 4, 5, 2, 2];
console.log(unique (s));
function unique (arr) {
let _flage=true;
const seen = new Map();
arr.filter((item) => {
if(_flage){
let key=(typeof item) + item;
if(!seen.has(key)){
seen.set(key, true);
}else{
_flage=false;
}
}
});
return _flage;
}