0

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 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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) ?? {}) 
}))

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.