我有两个对象数组(array1,array2)。我正在尝试返回最终数组(如下所示),它消除了array2中的重复项,但没有消除array1中的重复项。我将array1作为优先级。
array1 =[
{ phone: "07485454", name: "John" },
{ phone: "054554", name: "Ryan" },
]
array2 =[
{ phone: "2144564", name: "John" },
{ phone: "286456", name: "Mike" },
]
这是我最终想要的东西。仅从array2删除重复项。 最终数组:
[
{ phone: "07485454", name: "John" },
{ phone: "054554", name: "Ryan" },
{ phone: "286456", name: "Mike" },
]
这是我尝试过的事情:
for(let i = 0; i < array1.length; i++) {
let name = array1[i].name;
for(let a = 0; i < array2.length; a++) {
let newname = array2[a].name;
if(name !== newname) {
array1.push(
{
phone: array2[a].phone,
name: array2[a].name
});
}
console.log(array1);
}
}
这是我得到的错误。
"errorType": "TypeError",
"errorMessage": "Cannot read property 'name' of undefined",
答案 0 :(得分:0)
您已接近解决方案,可以创建一个Set来包含array1
元素的名称,并将array1
元素推入result
数组;随后将array2
中未包含名称的set
元素添加到result
数组中:
function removeDuplicates(array1, array2) {
const result = [];
const set = new Set();
for (const elem of array1) {
result.push(elem);
set.add(elem.name);
}
for (const elem of array2) {
if (!set.has(elem.name)) {
result.push(elem);
}
}
return result;
}
const array1 =[
{ phone: "07485454", name: "John" },
{ phone: "054554", name: "Ryan" }
];
const array2 =[
{ phone: "2144564", name: "John" },
{ phone: "286456", name: "Mike" }
];
console.log(JSON.stringify(removeDuplicates(array1, array2)));
答案 1 :(得分:0)
您在内部for循环条件中犯了错字 a
更改array1的长度将导致无限循环
每次,当 if(name!== newname)为真时,在array1中插入新对象将导致更改array1的长度。
let array1 =[
{ phone: "07485454", name: "John" },
{ phone: "054554", name: "Ryan" },
]
let array2 =[
{ phone: "2144564", name: "John" },
{ phone: "286456", name: "Mike" },
]
let result = array2.reduce((accumulator, currentItem) =>{
let index = accumulator.findIndex(item => item.name === currentItem.name);
if(index === -1){
accumulator.push(currentItem);
}
return accumulator;
},array1);
console.log(result);