reduce方法实现数组去重、数组对象去重

const responseList = [ 1,2,2,4,5,6,1,5,3,6]
console.log(uniqueBy(responseList,'a'));
function uniqueBy(arr, key) {
   return arr.reduce((acc,cur)=>{
     if (!acc.includes(cur)) {
       acc.push(cur)
     }
     return acc
   },[])
}
const responseList = [
  { id: 1, a: 1 },
  { id: 2, a: 2 },
  { id: 3, a: 3 },
  { id: 1, a: 4 },
  { id: 2, a: 2 },
  { id: 3, a: 3 },
  { id: 1, a: 4 },
  { id: 2, a: 2 },
  { id: 3, a: 3 },
  { id: 1, a: 4 },
  { id: 2, a: 2 },
  { id: 3, a: 3 },
  { id: 1, a: 4 },
]

console.log(uniqueBy(responseList,'id'));
function uniqueBy(arr, key) {
  return arr.reduce((acc,cur)=>{
    const values = acc.map(item => item[key])
    return values.includes(cur[key]) ? acc : [...acc,cur]
  },[])
}
posted @ 2021-11-23 17:13  Samsara315  阅读(111)  评论(0编辑  收藏  举报