0

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

2
  • 1
    Do items with same label have the same index in both arrays? Or can they be in random positions? Can label repeat in array? Commented May 31, 2019 at 18:02
  • I cannot guarantee that the items will have the same index in both arrays. The [tag: label] will not repeat.. it has to be unique Commented May 31, 2019 at 18:09

1 Answer 1

1

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.