Reputation: 121
I have an array of dates and a field with a number value. Now I am trying to use the reduce function to sort this out, I have googled a lot but I just cant find a solution.
The array i want to aggregate looks like this.
test = [
{
xUsed: 10,
date: "2021-01-01"
},
{
xUsed: 10,
date: "2021-01-01"
},
{
xUsed: 3,
date: "2021-01-02"
}
];
The result i want is this.
result [
{ xUsed: 20,
date: "2021-01-01 },
{ xUsed: 3,
date: "2021-01-02 }
]
This is the code I am trying to use
let res = this.test.reduce((acc, val ) => {
acc[val.date] + +val.xUsed;
return acc;
},[]);
But i get a typescript error 7015, Element implicitly has an 'any' type because index expression is not of type 'number' on acc[val.date]
Any idea?
Upvotes: 1
Views: 719
Reputation: 57929
A reduce it's easy. Take account you can use complex instructions
result=this.test.reduce((acc:any, val:any ) => {
//search in acc array if there're an element with the same "date"
const element=acc.find(x=>x.date==val.date)
if (!element) //if not exist
acc.push(val) //add the val to acc
else //if exist
element.xUsed+=val.xUsed //simple increment the xUsed property
return acc;
},[]);
Imagine reduce as a forEach. You're iterating and each iteration the "val" is one element of the array. It's like
const acc=[]; //<--this is the "initial value" (the last argument of reduce)
this.test.forEach(val=>{
const element=acc.find(x=>x.date==val.date)
if (!element)
acc.push(val)
else
element.xUsed+=val.xUsed
})
result=acc
Upvotes: 2