I am working with a database of jobs that are recorded daily, and I need to summarize the information grouped by company and obtain the sum of the progress of each task.
An example from the logs:
let trabajos = [{
faena: 'Mantención AAVC',
avance: 235,
medida: 'Metros',
empresa: 'Empresa Uno'
},
{
faena: 'Mantención AAVC',
avance: 125,
medida: 'Metros',
empresa: 'Empresa Uno'
},
{
faena: 'Mantención AAVC',
avance: 100,
medida: 'Metros',
empresa: 'Empresa Dos'
},
{
faena: 'Mantención Caminos',
avance: 2,
medida: 'Km',
empresa: 'Empresa Dos'
},
{
faena: 'Poda',
avance: 600,
medida: 'Metros',
empresa: 'Empresa Dos'
}]
What I am looking for as results would be something like this:
resumen = [{
empresa: 'Empresa Uno',
trabajos: [
{
faena: 'Mantención AAVC',
avance: 360,
medida: 'Metros',
}
]
},
{
empresa: 'Empresa Dos',
trabajos: [
{
faena: 'Mantención AAVC',
avance: 100,
medida: 'Metros'
},
{
faena: 'Mantención Caminos',
avance: 2,
medida: 'Km'
},
{
faena: 'Poda',
avance: 600,
medida: 'Metros'
}
]
}]
I tried with reduce() and filter() but I get an array with the different companies and a list of their jobs, and I got confused on how I can summarize the information to get each job with the sum of them by company.
const resp = trabajos.reduce((arrayTrabajo, trabajo) => {
const found = arrayTrabajo.find(a => a.empresa === trabajo.empresa);
const value = trabajo;
if (!found) {
arrayTrabajo.push({ empresa: trabajo.empresa, trabajos: [value] });
}
else {
found.trabajos.push(value);
}
return arrayTrabajo; }, []); console.log(resp);
Thank you!
With
reduce()
andfind()
you can get it.You need to find the company in the accumulator first, if it exists, then you need to find the job in that company's job list, and then add the advance there.
If the job doesn't exist, then you have to add a new job to the company's job list.
If the company does not exist, then you have to create the company with a job listing with the new job.