-1

I have two arrays as follows:

array1 = [
 {
  "id":"1",
   "name":"George",
   "City":"california"
 },
 {
  "id":"2",
   "name":"James",
   "City":"Paris"
 },
  {
  "id":"3",
  "name":"Julie",
  "City":"rome"
 }
]

array2 = [
 {
  "id":"2",
   "name":"jonty",
   "City":"wales"
 },
 {
  "id":"5",
   "name":"kite",
   "City":"mumbai"
 },
  {
  "id":"3",
  "name":"neha",
  "City":"pune"
 }
]

I want to check if any element with particular id in array2 exist in array1. If element with that id exist, then replace that element in array1 else push that element in array1. Final array will look as follows:

finalArray = [
{
  "id":"1",
   "name":"George",
   "City":"california"
 },
 {
  "id":"2",
   "name":"jonty",
   "City":"wales"
 },
  {
  "id":"3",
  "name":"neha",
  "City":"pune"
 },
 {
  "id":"5",
   "name":"kite",
   "City":"mumbai"
 }
]

How can I do that?

zaib7777
  • 89
  • 3
  • 14

1 Answers1

-1

This creates a duplicate of array one. It then loops over every item in array 2 and inserts it into the output array if it has a unique id. If it has the same id, then it replaces the item from array1 to array2.

const outArray = [...array1];

for (const item of array2)
{
    const { id } = item;
  
    const existingIndex = outArray.findIndex(element => element.id === id);

    if(existingIndex != -1) {
        outArray[existingIndex] = item;
    }
    else {
        outArray.push(item);
    }
}

// outArray is the output
User81646
  • 628
  • 4
  • 13