Reputation: 73
consider below 2 array of objects, say arr1 and arr2. based on id, if any new item exist in arr2 copy item to arr1 and remove item from arr1 if that item not present in arr2. Tried something like this,
const arr1 = [
{name: "name1", id: 1},
{name: "name2", id: 2},
{name: "name3", id: 3}
];
const arr2 = [
{name: "name1", id: 1},
{name: "name2", id: 4},
{name: "name3", id: 3}
];
const array1 = arr2.filter((val) => {
return arr1.find((val2) => {
const arr = [];
if (!arr1.includes(val.id)) {
arr.push(val);
}
});
});
console.log(array1)
required output
output = `[
{name: "name1", id: 1},
{name: "name3", id: 3},
{name: "name2", id: 4}
]`
Upvotes: -1
Views: 74
Reputation: 31
You can use below code:
const arr1 = [
{ name: "name1", id: 1 },
{ name: "name2", id: 2 },
{ name: "name3", id: 3 }
];
const arr2 = [
{ name: "name1", id: 1 },
{ name: "name2", id: 4 },
{ name: "name3", id: 3 }
];
var idsInArr2 = new Set(arr2.map(item => item.id));
// Remove items from arr1 that are not in arr2
var updatedArr1 = arr1.filter(item => idsInArr2.has(item.id));
// Create a set of IDs from updatedArr1 for quick lookup
var idsInUpdatedArr1 = new Set(updatedArr1.map(item => item.id));
// Add items to arr1 that are in arr2 but not in updatedArr1
arr2.forEach(item => {
if (!idsInUpdatedArr1.has(item.id)) {
updatedArr1.push(item);
}
});
console.log(updatedArr1);
Upvotes: 1
Reputation: 1586
EDIT:
Reduce method, based on "id" may be used but note that ordering does not comply with your expected result as commented below by Hao Wu
const arr1 = [
{name: "name1", id: 1},
{name: "name2", id: 2},
{name: "name3", id: 3}
];
const arr2 = [
{name: "name1", id: 1},
{name: "name2", id: 4},
{name: "name3", id: 3}
];
let output = arr2.reduce((a,b) => {
let a1 = arr1.find(e => e.id === b.id) || {};
return a.concat(Object.assign(a1, b));
},[]);
console.log(output)
Upvotes: 1