Ujith Isura
Ujith Isura

Reputation: 89

Create a new arrays of object using two object arrays using Node js

Let's have a look at an example.

var arr1 = new Array({team_id:1, name: "kamal", age: "18"},
                     {team_id:2, name: "nimal", age: "28"});

var arr2 = new Array({team_id:1, team_color : "red", team_name: 'team1'},
                     {team_id:2, team_color : "green", team_name: 'team2'}
                     {team_id:3, team_color : "blue", team_name: 'team3'});

I need to merge those 2 arrays of objects and create the following array:

var arr3 = new Array({team_id:1, name: "kamal", age: "18", team_color : "red", team_name:'team1'},
                     {team_id:2, name: "nimal", age: "28", team_id:2, team_color : "green", team_name: 'team2' });

As you can see in the above example I need to get the team details using the team_id to a single object array.

How can I achieve this using node js? Thanks in advance.

Upvotes: 1

Views: 58

Answers (2)

Durgesh
Durgesh

Reputation: 205

var arr1 = new Array({team_id:1, name: "kamal", age: "18"},
                     {team_id:2, name: "nimal", age: "28"});

var arr2 = new Array({team_id:1, team_color : "red", team_name: 'team1'},
                     {team_id:2, team_color : "green", team_name: 'team2'},
                     {team_id:3, team_color : "blue", team_name: 'team3'});

var mapOfTeams = new Map();    

arr2.forEach( a2 => mapOfTeams.set(a2.team_id, {team_color: a2.team_color, team_name: a2.team_name}));

var mergedArray = arr1.map(a1 => Object.assign(a1, mapOfTeams.get(a1.team_id)));
console.log(mergedArray);

O(m+n);

Upvotes: 0

bel3atar
bel3atar

Reputation: 943

var arr1 = new Array({
  team_id: 1,
  name: "kamal",
  age: "18"
}, {
  team_id: 2,
  name: "nimal",
  age: "28"
});

var arr2 = new Array({
  team_id: 1,
  team_color: "red",
  team_name: 'team1'
}, {
  team_id: 2,
  team_color: "green",
  team_name: 'team2'
}, {
  team_id: 3,
  team_color: "blue",
  team_name: 'team3'
});



const arr3 = arr1.map(x => ({
  ...x, 
  ...arr2.find(y => y.team_id === x.team_id) 
}))

console.log(arr3)

Upvotes: 3

Related Questions