返回不重复的数组值

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"},

];


慕码人8056858
浏览 133回答 1
1回答

ABOUTYOU

您可以使用Map和reduce首先创建一个mapper基于name并计算每个名称的重复次数只选择重复正好的值 1const 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)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript