-1
I have a backend application in Node that returns the following array:
let res= [
{
codigo: '0341',
codigo_1: '0320',
visao: '14',
total: 24,
data: '201502'
},
{
codigo:'0341',
codigo_1:'0320',
visao:'14',
total:25,
data: '201504'
},
{
codigo:'0321',
codigo_1:'0320',
visao:'14',
total:31,
data: '201506'
},
{
codigo:'0341',
codigo_1:'0320',
visao:'14',
total:55,
data: '201502'
},
]
The date attribute is composed by year/month, I can not change as it comes from the base so
I need the return grouped initially by date and then by code summing the totals, taking the following return:
[
{
data: '201502'
codigo: '0341'
total: 79
},
{
data: '201506'
codigo: '0321'
total: 31
},
{
data: '201504'
codigo: '0320'
total: 25
}
]
I have tried some forms, but without success. Follow:
const resultadosAgrupados = res.reduce(function (valorAcumulador, valorArray) {
if (!valorAcumulador[valorArray.data]) {
valorAcumulador[valorArray.data] = { ...valorArray };
return valorAcumulador;
}
valorAcumulador[valorArray.data].total += valorArray.total;
return valorAcumulador
}, [])
And also using uniqBy:
let teste = _.uniqBy(res, 'data')
Thank you.