I followed an example to use reduce and sum the values of some keys, but now, i want to sum values of an array of objects inside of this reduce...
This is what i have:
groupConceptos(){
var result = [];
this.auxTablaPrincipal.reduce((res, value, index) => {
var aux = [];
value.conceptoImpuesto.reduce((ant, nuevo) => {
if(!ant[nuevo.nombre]){
ant[nuevo.nombre] = {
base: 0,
importe: 0,
impuesto: nuevo.impuesto,
local: nuevo.local,
nombre: nuevo.nombre,
tasaOcuota: nuevo.tasaOcuota,
tipoFactor: nuevo.tipoFactor,
tipoImpuesto: nuevo.tipoImpuesto
};
aux.push(ant[nuevo.nombre])
}
ant[nuevo.nombre].base += parseFloat(nuevo.base);
ant[nuevo.nombre].importe += parseFloat(nuevo.importe);
return ant
}, {});
if(!res[value.descripcion]){
res[value.descripcion] = {
conceptoImpuesto: aux,//value.conceptoImpuesto,
cantidad: 0,
claveInterna: value.claveInterna,
claveProdServ: value.claveProdServ,
claveUnidad: value.claveUnidad,
descripcion: value.descripcion,
descuento: 0,
importe: 0,
subtotal: 0,
porcentajeIva: value.porcentajeIva,
precioPublico: value.precioPublico,
productoId: value.productoId,
sumaImporte: 0,
totalIva: value.totalIva,
totalPagado: value.totalPagado,
unidad: value.unidad,
valorUnitario: value.valorUnitario
};
result.push(res[value.descripcion])
}
res[value.descripcion].cantidad += parseInt(value.cantidad);
res[value.descripcion].descuento += parseInt(value.descuento);
res[value.descripcion].importe += parseFloat(value.importe);
res[value.descripcion].subtotal += parseFloat(value.subtotal);
res[value.descripcion].sumaImporte += parseInt(value.sumaImporte);
return res
}, {});
this.tablaPrincipal = result;
this.tablaPrincipal.forEach(element => {
element.conceptoImpuesto.forEach(concepto => {
this.auxConceptosImpuestos.push({
base: concepto.base,
importe: concepto.importe,
impuesto: concepto.impuesto,
local: concepto.local,
nombre: concepto.nombre,
tasaOcuota: concepto.tasaOcuota,
tipoFactor: concepto.tipoFactor,
tipoImpuesto: concepto.tipoImpuesto
})
});
});
},
* this.auxTablaPrincipal is an array that i use to reduce and assign to this.tablePrincipal
this.tablaPrincipal
is the result of the reduce of this.auxTablaPrincipal.
conceptoImpuesto
is an array of objects that i need to sum some values like this: res[value.descripcion].cantidad += parseInt(value.cantidad);
So i use the same method to reduce and sum value.conceptoImpuesto
of the reduce of this.auxTablaPrincipal
, and then assign aux
array to conceptoImpuesto
of the this.auxTablaPrincipal
But this method is not working.
How to sum values of an array inside of a reduce method?
EDIT
For example, i use reduce to group values if a new value is the same that its present in the array. So i want to sum values of a the conceptoImpuesto
array to apply the sum of the conceptoImpuesto.
In the image the value of "canatidad" is 2. So, the values of "base" and "importe" of the array conceptoImpuesto
add up, like i do in the code