一、普通数组去重:利用es6的new Set实现
const arr1 = [1,2,3]
const arr2 = [3,4,5]
const resultArr = [...new Set([...arr1,...arr2])]
二、对象数组去重:利用数组方法reduce获得
1. reduce使用方法
2. 代码实现
const arr1 = [
{ id:1, name: '牛奶' },
{ id:2, name: '面包' }
]
const arr2 = [
{ id:1, name: '牛奶' },
{ id:3, name: '花生' }
]
const newDatas = [...arr1, ...arr2]
const hash = {}
const arr = newDatas.reduce((item, next) => {
hash[next.id] ? '' : (hash[next.id] = true && item.push(next))
return item
}, [])