JavaScript - Merge two arrays according to id property


Suppose we have two arrays of objects, the first of which contains some objects with user ids and user names.

The array contains objects with user ids and user addresses.

The array is −

const arr1 = [
   {"id":"123","name":"name 1"},
   {"id":"456","name":"name 2"}
];
const arr2 = [
   {"id":"123","address":"address 1"},
   {"id":"456","address":"address 2"}
];

We are required to write a JavaScript function that takes in two such arrays and merges these two arrays to form a third array.

The third array should contain the user id, name, and address object of corresponding users.

Example

The code for this will be −

const arr1 = [
   {"id":"123","name":"name 1"},
   {"id":"456","name":"name 2"}
];
const arr2 = [
   {"id":"123","address":"address 1"},
   {"id":"456","address":"address 2"}
];
const mergeArrays = (arr1 = [], arr2 = []) => {
   let res = [];
   res = arr1.map(obj => {
      const index = arr2.findIndex(el => el["id"] == obj["id"]);
      const { address } = index !== -1 ? arr2[index] : {};
      return {
         ...obj,
         address
      };
   });
   return res;
};
console.log(mergeArrays(arr1, arr2));

Output

And the output in the console will be −

[
   { id: '123', name: 'name 1', address: 'address 1' },
   { id: '456', name: 'name 2', address: 'address 2' }
]

Updated on: 23-Nov-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements