为了账号安全,请及时绑定邮箱和手机立即绑定

返回不重复的数组值

返回不重复的数组值

慕码人8056858 2021-11-18 20:55:26
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)


查看完整回答
反对 回复 2021-11-18
  • 1 回答
  • 0 关注
  • 131 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信