-1
I have the following array:
const array = [
  { a: 1, b: 2 },
  { a: 1, b: 1 },
  { a: 3, b: 4 }
];
I would like a second array to be generated for each time I repeat the attribute to, generates a new element where the to retains its value, and the b add with the b of the second index of the array, resulting in this array below:
[
  { a: 1, b: 3 },
  { a: 3, b: 4 }
];
For that, I used the reduce of javascript, as follows:
const array = [
  { a: 1, b: 2 },
  { a: 1, b: 1 },
  { a: 3, b: 4 }
];
const result = [];
array.reduce((acc, cur)=>{
  let response = {};
  if(acc.a === cur.a){
    response.a = cur.a;
    response.b = acc.b + cur.b;
  }else{
    response = cur;
  }
  result.push(response);
  return cur;
},0);
console.log(result)
As a result:
[ { a: 1, b: 2 }, { a: 2, b: 3 }, { a: 3, b: 4 } ]
How do I make my result :
[ { a: 2, b: 3 }, { a: 3, b: 4 } ]
Using Javascript and reduce;
OBS: the array shown in the above example is only an example, the original is quite extensive and also dynamic. Therefore, I used reduce to access the past and past items of each index of that array.
But what is the intended result? It is
[ { a: 1, b: 3 }, { a: 3, b: 4 } ]or[ { a: 2, b: 3 }, { a: 3, b: 4 } ]?– Augusto Vasques