
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 with Objects in One in JavaScript
Suppose, we have two arrays of objects like these −
const arr1 = [ {name:'test', lastname: 'test', gender:'f'}, {name:'test1', lastname: 'test1', gender:'f'}, {name:'test2', lastname: 'test2', gender:'m'} ]; const arr2 = [ {name:'test21', lastname: 'test21', gender:'f'}, {name:'test1', lastname: 'test1', gender:'f'}, {name:'test2', lastname: 'test2', gender:'m'}, {name:'test22', lastname: 'test22', gender:'m'} ];
These arrays do not have any repeating objects within (repeating on the basis of 'name' property) but there exist some objects with repeating names in the first and second objects.
We are required to write a JavaScript function that takes two such arrays and returns a new array.
The new array should contain all the unique objects of both the first and second array. Here, to check the uniqueness of any object we will check for its unique "name" property.
Example
The code for this will be −
const arr1 = [ {name:'test', lastname: 'test', gender:'f'}, {name:'test1', lastname: 'test1', gender:'f'}, {name:'test2', lastname: 'test2', gender:'m'} ]; const arr2 = [ {name:'test21', lastname: 'test21', gender:'f'}, {name:'test1', lastname: 'test1', gender:'f'}, {name:'test2', lastname: 'test2', gender:'m'}, {name:'test22', lastname: 'test22', gender:'m'} ]; const mergeUniquely = (arr1 = [], arr2 = []) => { const newArr = arr1.concat(arr2); const map = {}; const res = []; newArr.forEach(el => { if(!map[el['name']]){ res.push(el); map[el['name']] = 1; }; }); return res; }; console.log(mergeUniquely(arr1, arr2));
Output
And the output in the console will be −
[ { name: 'test', lastname: 'test', gender: 'f' }, { name: 'test1', lastname: 'test1', gender: 'f' }, { name: 'test2', lastname: 'test2', gender: 'm' }, { name: 'test21', lastname: 'test21', gender: 'f' }, { name: 'test22', lastname: 'test22', gender: 'm' } ]
Advertisements