数组、数组对象去重

1.reduce去重

语法:reduce(callback,initVal,allArr) initVal为初始值,allArr为原数组
举例:

let a = [1,2,3,2,5,2,6,3];
a.reduce((pre,cur)=>{
  if(pre.includes(cur)){
    return pre  
}else{
  return pre.concat(cur)
}
},[])
// [1, 2, 3, 5, 6]
let b =[
        {
          name:'红红',
          id:'121'
        },
        {
          name:'绿绿',
          id:'120'
        },{
          name:'红红',
          id:'121'
        },{
          name:'兰兰',
          id:'132'
        }
      ];
 let temp =[];
 b.reduce((pre,cur)=>{
   if(temp.includes(cur.id) == false){
      temp = temp.concat(cur.id);
      return pre.concat(cur)
   }
  return pre;
 }, [])
//结果:  [{name:'红红', id:'121' },{name:'绿绿',id:'120'},{name:'兰兰',id:'132'}];

你可能感兴趣的:(数组、数组对象去重)