var arr = [ {name:"Grace", age: "28"}, {name:"Peter", age: "15"}, {name:"Grace", age: "28"}, {name:"John", age: "16"}, {name:"Prince", age: "19"}, {name:"John", age: "16"} ]; 我现在只想返回那些独特的如下var new = [ {name:"Peter", age: "15"}, {name:"Prince", age: "19"},];
1 回答
ABOUTYOU
TA贡献1812条经验 获得超5个赞
您可以使用Map和reduce
首先创建一个mapper基于name并计算每个名称的重复次数
只选择重复正好的值 1
const arr = [{name:"Grace", age: "28"},{name:"Peter", age: "15"},{name:"Grace", age: "28"},{name:"John", age: "16"},{name:"Prince", age: "19"},{name:"John", age: "16"}];
let mapper = arr.reduce( (op,inp) => {
let {name:key} = inp
op.set(key, op.get(key) || {value: inp, count:0})
op.get(key).count++
return op
},new Map())
let final = [...mapper.values()].reduce((op,{value,count}) => {
if(count === 1){
op.push(value)
}
return op
},[])
console.log(final)
添加回答
举报
0/150
提交
取消