0
votes

Is there an efficient way of creating a new array from 2 arrays?

var employees1 = [
{ id: 11, name: 'joe' },
{ id: 12, name: 'mike' },
{ id: 13, name: 'mary' },
{ id: 14, name: 'anne' }
];

var employees2 = [
{ id: 11, message: 'test1' },
{ id: 12, message: 'test2' },
{ id: 13, message: 'test3' },
{ id: 14, message: 'test4' }
];

Iterate employees1 array and get 'message' for matching id from employees2. Resulting in new array:

var employees3 = [
{ id: 11, name: 'joe', message: 'test1' },
{ id: 12, name: 'mike', message: 'test2' },
{ id: 13, name: 'mary', message: 'test3' },
{ id: 14, name: 'anne', message: 'test4' }
];

Is this possible using Map function? Or using a standard foreach suggested?

2

2 Answers

1
votes

Iterate over the first array, search for the element in the second array and finally push them to the new array as illustrated below:

var employees3 = [];

employees1.forEach(emp1 => {
  const findEmp = employees2.find(emp2 => emp2.id === emp1.id);
  if (findEmp) {
    employees3.push({
      ...emp1,
      ...findEmp
    });
  }
});

console.log(employees3);
1
votes

You can use Array#map and Array#find to get the desired output. I am attaching a sample code:

var employees3 = employees1.map(emp => ({ 
  ...emp, 
  ...(employees2.find(item => item.id === emp.id) ?? {}) 
}))