1

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.

2 Answers 2

3

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)

Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.