Home > Mobile >  Compare the two arrays and replace/merge the values for id present in the other array (js)
Compare the two arrays and replace/merge the values for id present in the other array (js)

Time:09-16

I have two arrays, and I want to be able to compare the two and replace the object values for id present in the info array with the details array and populate the rest as it is. I haven't found anything like this. What would be the best way to return similarities?

const details = [{
    id: "id1",
    description: "new description-1"
  },
  {
    id: "id3",
    linkUrl: "new link-1"
  }
]

const info = [{
    id: "id1",
    description: "old description-1",
    linkUrl: "#id1link-1",
    image: "#imageUrl-1"
  },
  {
    id: "id2",
    description: "description-2",
    linkUrl: "#id1link-2",
    image: "#imageUrl-2"
  },
  {
    id: "id3",
    description: "description-3",
    linkUrl: "#old link-2",
    image: "#imageUrl-2"
  }
]

const result = [{
    id: "id1",
    description: "new description-1",
    linkUrl: "#id1link-1",
    image: "#imageUrl-1"
  },
  {
    id: "id2",
    description: "description-2",
    linkUrl: "#id1link-2",
    image: "#imageUrl-2"
  },
  {
    id: "id3",
    description: "description-3",
    linkUrl: "#new link-2",
    image: "#imageUrl-2"
  }
]

CodePudding user response:

Using map, Find and Destructuring assignment.

const result = info.map(item => {
    const new_info = details.find(detail => detail.id === item.id);

    return {
        ...item,
        ...new_info,
    };
})

CodePudding user response:

For larger amounts of data, it is best to first create a map for the details data, so that retrieving an id can happen in constant time:

const details = [{id:"id1",description: "new description-1"},{id: "id3",linkUrl: "new link-1"}];
const info = [{id: "id1",description: "old description-1",linkUrl: "#id1link-1",image: "#imageUrl-1"},{id: "id2",description: "description-2",linkUrl: "#id1link-2",image: "#imageUrl-2"},{id: "id3",description: "description-3",linkUrl: "#old link-2",image: "#imageUrl-2"}];

const map = new Map(details.map(({id, ...rest}) => [id, rest]));
const result = info.map(o => ({...o, ...map.get(o.id)}));

console.log(result);

  • Related