
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
Add Two JavaScript Arrays of Objects and Replace Repeated Members
We have the following arrays of objects, we need to merge them into one removing the objects that have redundant value for the property name −
const first = [{ name: 'Rahul', age: 23 }, { name: 'Ramesh', age: 27 }, { name: 'Vikram', age: 35 }, { name: 'Harsh', age: 34 }, { name: 'Vijay', age: 21 }]; const second = [{ name: 'Vijay', age: 21 }, { name: 'Vikky', age: 20 }, { name: 'Joy', age: 26 }, { name: 'Vijay', age: 21 }, { name: 'Harsh', age: 34 }, ]
We define a function combineArray, take in the two arrays to be combined as arguments and return a new array −
const combineArray = (first, second) => { const combinedArray = []; const map = {}; first.forEach(firstEl => { if(!map[firstEl.name]){ map[firstEl.name] = firstEl; combinedArray.push(firstEl); } }); second.forEach(secondEl => { if(!map[secondEl.name]){ map[secondEl.name] = secondEl; combinedArray.push(secondEl); } }) return combinedArray; } console.log(combineArray(first, second));
This function not only makes sure to remove duplicate entries from the second array, moreover had there existed any duplicate entry in the first array, it would have removed that as well.
Here’s the complete code −
Example
const first = [{ name: 'Rahul', age: 23 }, { name: 'Ramesh', age: 27 }, { name: 'Vikram', age: 35 }, { name: 'Harsh', age: 34 }, { name: 'Vijay', age: 21 }]; const second = [{ name: 'Vijay', age: 21 }, { name: 'Vikky', age: 20 }, { name: 'Joy', age: 26 }, { name: 'Vijay', age: 21 }, { name: 'Harsh', age: 34 }, ] const combineArray = (first, second) => { const combinedArray = []; const map = {}; first.forEach(firstEl => { if(!map[firstEl.name]){ map[firstEl.name] = firstEl; combinedArray.push(firstEl); } }); second.forEach(secondEl => { if(!map[secondEl.name]){ map[secondEl.name] = secondEl; combinedArray.push(secondEl); } }) return combinedArray; } console.log(combineArray(first, second));
Output
The console output will be −
[ { name: 'Rahul', age: 23 },{ name: 'Ramesh', age: 27 },{ name: 'Vikram', age: 35 }, { name: 'Harsh', age: 34 },{ name: 'Vijay', age: 21 },{ name: 'Vikky', age: 20 }, { name: 'Joy', age: 26 } ]
Advertisements