Reputation: 37
Considering the two arrays bellow:
let aaa = [{label: "nu", angle: 5}, {label: "na", angle: 3}]
let bbb= [{label: "nu", angle: 2}, {label: "na", angle: 6}]
How can I add the value on the angle key from one object with the corresponding one from the next array of objects and return one object or the other.
the result should be:
let ccc= [{label: "nu", angle: 7}, {label: "na", angle: 9}]
I have no idea how to solve this
Upvotes: 0
Views: 40
Reputation: 12964
You can use Array.reduce()
and Array.findIndex()
like this:
let aaa = [{label: "nu", angle: 5}, {label: "na", angle: 3}];
let bbb= [{label: "nu", angle: 2}, {label: "na", angle: 6}];
const ccc = [...aaa, ...bbb].reduce((acc, a) => {
const i = acc.findIndex(o => o.label === a.label);
if(i === -1) { acc.push(a); return acc; }
acc[i].angle += a.angle;
return acc;
}, []);
console.log(ccc);
Upvotes: 1