js数组去重
2017-04-21 本文已影响23人
我不叫奇奇
数组去重几种常用的方式:
- 创建两个数组,每一个元素都在新数组里寻找一次,两次for循环(效率低,不推荐);
- 使用indexOf,查找重复元素并删除,一次for循环。(推荐);
- 引申,为Array拓展新方法。(推荐)
- 定义去重数组,用call调用。 (推荐)
- es6的set方法(推荐)
两次for循环:
var arr = [1,2,3,4,1,2,5,3,6,4,7,9,3,2,4,9,1,1];
var newArr = [];
for(var i=arr.length-1;i>=0;i--){
for(var j=0;j<=newArr.length;j++){
if(arr[i]==newArr[j]){
break;
}else if(j==newArr.length){
newArr.push(arr[i])
break;
}
}
}
console.log(newArr);//Array [ 1, 2, 3, 4, 5, 6, 7, 9 ]
使用indexOf:
var arr = [1,2,3,4,1,2,5,3,6,4,7,9,3,2,4,9,1,1];
for(var i = 0;i<arr.length;i++){
while((a = arr.indexOf(arr[i],i+1)) != -1){
arr.splice(a,1);
}
}
console.log(arr);//Array [ 1, 2, 3, 4, 5, 6, 7, 9 ]
为Array拓展:
var arr = [1,2,3,4,1,2,5,3,6,4,7,9,3,2,4,9,1,1];
Array.prototype.disrepeat = function(){
var newArr = [];
for(var i = 0;i<this.length;i++){
if(newArr.indexOf(this[i])==-1){
newArr.push(this[i]);
}
}
return newArr;
}
var result = arr.disrepeat();
console.log(result);//Array [ 1, 2, 3, 4, 5, 6, 7, 9 ]
用call调用:
function disrepeat(){
var newArr = [];
for(var i = 0;i<this.length;i++){
if(newArr.indexOf(this[i])==-1){
newArr.push(this[i]);
}
}
return newArr;
}
var result = disrepeat.call(arr);
console.log(result);//Array [ 1, 2, 3, 4, 5, 6, 7, 9 ]
es6的set方法
//plan A
let arr = [1,2,3,4,2,3,2,3]
function disrepeat(arr) {
return [...new Set(arr)]
}
console.log('arr',disrepeat(arr))// arr [1,2,3,4]
// plan B
let arr2 = [2,3,3,2,1,3,4,5,1,3]
function disrepeat2(arr){
return Array.from(new Set(arr)).sort()
}
console.log('arr2',disrepeat2(arr2))// arr2 [1,2,3,4,5]