 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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' } ]Advertisements
 