方法一:利用filter
var arr=[{id:1,name:'bob'},{id:1,name:'bob'},{id:1,name:'bob'},{id:1,name:'lucy'},{id:1,name:'lucy'},{id:2,name:'lucy'},{id:2,name:'张三'}]
//去掉相同id的项目
var arr1=arr.filter(function(element,index,self){
return self.findIndex(el=>el.id==element.id)===index
})
//封装成方法,通过某个属性去重
function filterRepeat(arr,prop){
return arr.filter(function(element,index,self){
return self.findIndex(el=>el[prop]==element[prop])===index
})
}
//自定义去重方法
function filterRepeat2(arr,compareFn){
return arr.filter(function(element,index,self){
return self.findIndex(el=>compareFn(el,element))===index
})
}
//加载到数组原型上
Array.prototype.filterRepeat=function(){
if(typeof arguments[0]=='string') return filterRepeat(this,arguments[0])
return filterRepeat2(this,arguments[0])
}
//test 通过name属性去重
var newArr=arr.filterRepeat('name')
console.log(newArr)
var newArr2=arr.filterRepeat(function(a,b){return a.id==b.id&&a.name==b.name})
console.log(newArr2)
测试结果
image.png
方法二:利用reduce
var arr=[{id:1,name:'bob'},{id:1,name:'bob'},{id:1,name:'bob'},{id:1,name:'lucy'},{id:1,name:'lucy'},{id:2,name:'lucy'},{id:2,name:'张三'}]
var arr1=arr.reduce(function(prev,element){
if(!prev.find(el=>el.id==element.id)) {
prev.push(element)
}
return prev
},[])
网友评论