I have two JavaScript arrays:
let array1 = [{name:'jane', age: 20}, {name:'john', age: 30}];
let array2 = [{name:'bob', age: 50}, {name:'john', age: 25}];
I want the output to be:
let result = [{name:'jane', age: 20},{name:'bob', age: 50}, {name:'john', age: 55}];
The output array should combine john's age (30 25) since john is a duplicate.
How to merge two arrays of objects in JavaScript and combine any objects that have the same name and add the age.
CodePudding user response:
You can use 2 for loops to access the arrays and verify if is the same name, when is the same name, you change the old object to the new. like this:
let array1 = [{name:'jane', age: 20}, {name:'john', age: 30}];
let array2 = [{name:'bob', age: 50}, {name:'john', age: 25}];
for(let i in array1){
for(let j in array2){
if(array1[i].name == array2[j].name){
let newAge = array2[j].age array1[i].age
array2[j] = {name: array2[j].name, age: newAge}
}
}
}
console.log(array2);
CodePudding user response:
May be a little cryptic but it's fun:
Object.values(
[...array1, ...array2].reduce((p, c) => ({...p, [c.name]: {...c, age: (p[c.name]?.age || 0) c.age}}), {}),
);
CodePudding user response:
You can use grouping approach:
const array1 = [{name:'jane', age: 20}, {name:'john', age: 30}];
const array2 = [{name:'bob', age: 50}, {name:'john', age: 25}];
const grouped = [...array1, ...array2].reduce((acc, { name, age }) => {
acc[name] ??= { name, age: 0 };
acc[name].age = age;
return acc;
}, {});
const result = Object.values(grouped);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0 }