skip to Main Content

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


  1. 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.

    let arr3 = arr1.map(item1 => {
      const matchingItem = arr2.find(item2 => item2.id === item1.id);
      if (matchingItem) {
        return { ...item1, ...matchingItem };
      }
      return null;
    }).filter(item => item !== null);
    
    let arr1 = [
    { id: "123", name: "John" }, 
    { id: "345", name: "Sara" },
    { id: "542", name: "Jack" },
    ];
    
    let arr2 = [
    { id: "123", phone: "021456" },
    { id: "345", phone: "0911256" }
    ];
    
    
    let arr3 = arr1.map(item1 => {
      const matchingItem = arr2.find(item2 => item2.id === item1.id);
      if (matchingItem) {
        return { ...item1, ...matchingItem };
      }
      return null;
    }).filter(item => item !== null);
    
    console.log(arr3);
    Login or Signup to reply.
  2. You can use reduce, find and spread operator (...) to achieve this.

    let arr3 = arr2.reduce((acc, item) => {
        arr1.find((i) => {
            if (i.id === item.id) acc.push({...item, ...i});
        }) 
        return acc;
    }, []);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search