- filter去重
var arr=[
{id:1,name:'F1'},
{id:1,name:'F1'},
{id:1,name:'F1'},
{id:1,name:'F2'},
{id:1,name:'B2'},
{id:2,name:'F1'},
{id:2,name:'F6'}
]
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
})
}
调用 filterRepeat(arr, 'id');
console.log(arr1, filterRepeat(arr, 'id'))
- 利用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
},[])
console.log(arr1)