I have two arrays and I want to merge items that their id are same and remove the others. For example: Array 1:
let arr1 = [
{ id: "123", name: "John" },
{ id: "345", name: "Sara" },
{ id: "542", name: "Jack" },
]
and Array 2 :
let arr2 = [
{ id: "123", phone: "021456" },
{ id: "345", phone: "0911256" }
]
and I need to merge these 2 arrays based on id and get this:
let arr3 =[
{ id: "123", phone: "021456", name: "John" },
{ id: "345", phone: "0911256", name: "Sara" }
]
How can I do this? I run the below code but unfortunately I have the third item but I do not want to have it
let arr3 = arr1.map((item, i) => Object.assign({}, item, arr2[i]));
console.log(arr3);
2
Answers
I used map() and find() methods to merge two arrays based on the matching id property, creating a new array with the merged items while filtering out any unmatched items.
You can use
reduce
,find
andspread operator (...)
to achieve this.