My question is how can I:
- Add the properties of an object --pj: {id:1, value:2, quantity:3} --> 2 x 3 = 6
- After that compare if an object inside the array is equal to the id of the previous object pj--> {id:1, value:2, quantity:3}{id:1, value:3, quantity:4} --> true
- And if that object is equal to the previous one before adding it, you have to first count its value and quantity pj {category:"customer", value:2, accumulated:3} {id:1, value:3, accumulated: 4} --> (2 x 3) + (3 x 4) = 18
- Finally the code would have to have the added values of each object and reduced to a single object --> example {category:"customer", finalValue: 24} and push to the array
resultado final = [{categoria: "customer", valorFinal=24}, {categoria: "company", valorFinal=15}]
I did this code with reduce but it is not coming out
const obj = [
{
categoria: 'customer',
valor: 2,
acumulado: 3,
},
{
categoria: 'customer',
valor: 2,
acumulado: 3,
},
{
categoria: 'customer',
valor: 2,
acumulado: 3,
},
{
categoria: 'customer',
valor: 2,
acumulado: 3,
},
{
categoria: 'company',
valor: 5,
acumulado: 3,
},
]
const acumulador = (obj) => {
let resultado = 0;
const valores = obj.reduce((acumulador, valorActual) => {
const elementoYaExiste = acumulador.find(elemento => elemento.categoria === valorActual.categoria);
if (elementoYaExiste) {
return acumulador.map(elemento => {
if (elemento.categoria === valorActual.categoria) {
resultado = resultado += (elemento.valor * valorActual.acumulado);
console.log(resultado)
return{
...elemento,
cantidad: resultado
}
}
})
}
return [...acumulador, valorActual];
}, []);
console.log(valores)
};
acumulador(obj)
You can do it like this (Code commented):