G
No need to use the method https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce to get what you want. In fact it is not the most suitable method for generating a set of objects, in their documentation reduce() is defined so:The method reduce() performs a reducing function, provided by you, for
each element of the array, resulting in a single return value.That is you are diverting the purpose of using the method reduce() because you are not trying to reduce the input elements to a single object and yes to several.Unless it is a challenge to see that it makes the biggest gambiarra to add a certain field of various objects having as reference other field of these objects, it is enough only to iterate by the array with https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach , or use a simple https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Statements/for how he remembered https://pt.stackoverflow.com/users/112052/hkotsubo , and go adding the respective values b with the values already stored in a result array where the index is a. Follow the commented example://Array de testes
let arr =[
{ a: 1, b: 2 },
{ a: 1, b: 5 },
{ a: 1, b: 1 },
{ a: 1, b: 1 },
{ a: 11, b: 11 },
{ a: 3, b: 4 },
{ a: 3, b: 4 },
{ a: 3, b: 4 },
{ a: 3, b: 4 },
{ a: 3, b: 4 },
{ a: 3, b: 41 },
{ a: 13, b: 41 }
];
//Array que receberá o resultado
let result = [];
//Para todos os elementos de arr
arr.forEach(item =>{
//Se result não tiver o índice item.a definido inicializa result[item.a]
if (result[item.a] == undefined) result[item.a] = {"a":item.a, "b":0};
//Soma item.b ao seu respectivo elemento em result
result[item.a].b += item.b;
});
//Remove os indices não utilizados de result
result = result.filter(item => !!item);
console.log(result);