0

I am working on an angular application. I have two arrays as follows:

array1 = [
  {
    Name: "Jack",
    Id: "1",
    Location: "UK"
  },
  {
    Name: "Rose",
    Id: "2",
    Location: "USA"
  },
  {
    Name: "Mary",
    Id: "3",
    Location: "India"
  }
];

array2 = [
  {
    Name: "Raj",
    Id: "5",
    Location: "UK"
  },
  {
    Name: "John",
    Id: "2",
    Location: "Germany"
  },
  {
    Name: "Maria",
    Id: "3",
    Location: "Canada"
  }
];

I want a resultant array such that If "Id" of any element of array1 matches "Id" of any element in array2, then whole data for that particular "Id" should be replaced in array2. So my resulArray will look as follows:

resultArray = [
  {
    Name: "Raj",
    Id: "5",
    Location: "UK"
  },
  {
    Name: "Rose",
    Id: "2",
    Location: "USA"
  },
  {
    Name: "Mary",
    Id: "3",
    Location: "India"
  }
];

So Id= 2 and Id =3 of array 1 matches in array2, so data of Id=2 and Id=3 in array2 are replaced by that of array1. How can I do it?

Raghul SK
  • 1,256
  • 5
  • 22
  • 30

2 Answers2

3

You need map and find here. You can put an OR condition that if value is present in array1 if so then will pick the object from array1 otherwise the current object will be chosen.

var array2=[ { "Name": "Raj", "Id": "5", "Location": "UK" }, { "Name": "John", "Id": "2", "Location": "Germany" }, { "Name": "Maria", "Id": "3", "Location": "Canada" }];

var array1= [{ "Name": "Jack", "Id": "1", "Location": "UK"},{ "Name": "Rose", "Id": "2", "Location": "USA"},{ "Name": "Mary", "Id": "3", "Location": "India"}];

var result = array2.map(p=>(array1.find(k=>k.Id==p.Id) || p));

console.log(result);

I hope this helps.

gorak
  • 5,233
  • 1
  • 7
  • 19
1

You can use reduce and find function for your requirement

array2.reduce((acc, c) => {
  var existed = array1.find(a=>a.Id == c.Id);
  if(existed){
     c.Name = existed.Name;
  }
  return c;
}, [])

var array1= [
{
   "Name": "Jack",
   "Id": "1",
   "Location": "UK"
},
{
   "Name": "Rose",
   "Id": "2",
    "Location": "USA"
},
{
   "Name": "Mary",
   "Id": "3",
   "Location": "India"
}
]

var array2=[
 {
       "Name": "Raj",
       "Id": "5",
       "Location": "UK"
    },
    {
       "Name": "John",
       "Id": "2",
        "Location": "Germany"
    },
    {
       "Name": "Maria",
       "Id": "3",
       "Location": "Canada"
    }
];


array2.reduce((acc, c) => {
  var existed = array1.find(a=>a.Id == c.Id);
  if(existed){
     c.Name = existed.Name;
  }
  return c;
}, [])

console.log(array2)
Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62