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}
]`
2
Answers
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