
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
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
Merge Two Arrays According to ID Property in JavaScript
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