根据数组中某个对象唯一标识完成去重
//原数据
var arr = [
{
id:'1',
name:'a'
},
{
id:'2',
name:'b'
},
{
id:'1',
name:'abc'
}
]
//根据id去重后数据
var arr1 = [
{
id:'1',
name:'a'
},
{
id:'2',
name:'b'
}
]
1.filter
//使用filter
function uniqueFunc(arr, uniId){
const res = new Map();
return arr.filter((item) => !res.has(item[uniId]) && res.set(item[uniId], 1));
}
console.log(uniqueFunc(arr,'id'))
2.reduce
//使用reduce
function uniqueFunc2(arr, uniId){
let hash = {}
return arr.reduce((accum,item) => {
hash[item[uniId]] ? '' : hash[item[uniId]] = true && accum.push(item)
return accum
},[])
}
console.log(uniqueFunc2(arr,'id'))
3.for循环
//for循环
function uniqueFunc3(arr, uniId){
let obj = {}
let tempArr = []
for(var i = 0; i<arr.length; i++){
if(!obj[arr[i][uniId]]){
tempArr.push(arr[i])
obj[arr[i][uniId]] = true
}
}
return tempArr
}
console.log(uniqueFunc3(arr,'id'))