例如两个数组根据id字段去重
//数组1
let arr1 = [
{
id: 1,
name: "张三",
age: 18
},
{
id: 2,
name: "李四",
age: 18
},
{
id: 3,
name: "王五",
age: 18
}
];
// 数组2
let arr2 = [
{
id: 1,
name: "张三"
},
{
id: 2,
name: "李四"
}
];
arr1.push(...arr2); //合并数组
console.log(arr1);
输出如下图所示:
这个时候的合并的数组是有重复的,需要我们根据id的唯一值来筛选数组,所以我们需要在上面的代码上再加如下代码
let hash = {}; //去重
let arr = arr1.reduce((preVal, curVal) => {
hash[curVal.id] //id就是数组中的id字段
? ""
: (hash[curVal.id] = true && preVal.push(curVal));
return preVal;
}, []);
console.log(arr);