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 } ]