如何合并两个对象数组并移除其中的重复对象元素
实现思路
对象数组无法直接用Set去重,你需要先定义重复判断规则,从示例来看只要name和std两个属性同时相同就算重复,我们可以通过唯一标识标记重复项实现去重。
方法1:Map实现(推荐,大数据量性能更好)
Map的查询复杂度为O(1),适合处理元素较多的场景,默认保留先出现的重复项:
let arr1 = [ { name: 'abc', std: '1' }, { name: 'abc1', std: '2' }, { name: 'abc2', std: '3' }, ] let arr2 = [ { name: 'abc3', std: '1' }, { name: 'abc4', std: '2' }, { name: 'abc2', std: '3' }, ] const uniqueMap = new Map() // 合并两个数组后遍历 ;[...arr1, ...arr2].forEach(item => { // 用name和std拼接成唯一key const uniqueKey = `${item.name}-${item.std}` // 不存在该key时才存入,要保留后出现的重复项可删除判断直接set if (!uniqueMap.has(uniqueKey)) { uniqueMap.set(uniqueKey, item) } }) // 提取Map的值转为数组就是最终结果 const finalArr = Array.from(uniqueMap.values()) console.log(finalArr)
方法2:reduce + find实现(小数据量写法更直观)
如果数组元素不多,用reduce遍历配合find判断是否已存在即可,逻辑更易读:
const finalArr = [...arr1, ...arr2].reduce((result, current) => { // 判断当前项是否已经在结果数组中存在 const existed = result.find(item => item.name === current.name && item.std === current.std ) if (!existed) { result.push(current) } return result }, [])
自定义规则调整
如果实际场景只需要按name单一属性判断重复,修改上面的唯一key或者find的判断条件即可。
内容的提问来源于stack exchange,提问作者divyraj
相关产品推荐
相关产品推荐

