案例要求:

如有以下两个用户数组,把用户Id相同的过滤掉,然后合并成新的数组

let users1 = [
 {id:1, name:'tom', age: 20},
 {id:2, name:'jack', age: 21},
 {id:3, name:'smith', age: 22}
]

let users2 = [
 {id:3, name:'smith', age: 22},
 {id:4, name:'rose', age: 23},
 {id:5, name:'tina', age: 24},
]

合并后

[
 {id:1, name:'tom', age: 20},
 {id:2, name:'jack', age: 21},
 {id:3, name:'smith', age: 22},
 {id:4, name:'rose', age: 23},
 {id:5, name:'tina', age: 24},
]

实现

先使用…合并成一个新的数组,然后使用reduce方法去除对象中id相同的值

let newArr = [...users1, ...users2]
let obj = {}
let newUsers = newArr.reduce((item, next) => {
  obj[next.id] ? '' : obj[next.id] = true && item.push(next)
  return item
}, [])