So I have an array of transactions that looks like this:
[
{
date: '22-03-2021,
amount: 2,
value: 10,
fees: 0.1,
type: "BUY"
transactionId: '21412412',
}
]
And what I want to do with the array is two things...
One is get an array of objects per date. Summing the value property of objects that are of type 'BUY' and deducting the value property from objects of type 'SELL'. Eventually I will need to deal with other transaction types, but not now...
Example: (you can see the value rise and fall, due to SELL and BUY both taking place)
[
{
date: "04-06-2021",
value: 20.0,
},
{
date: "05-06-2021",
value: 28.99,
},
{
date: "06-06-2021",
value: 47.99,
},
{
date: "07-06-2021",
value: 37.99,
},
{
date: "08-06-2021",
value: 42.29,
},
]
Two is pretty similar. I want to generate an array of objects per date but associated to a particular ticker.
Example: (value rises due to only BUY taking place)
[
{
TSLA: [
{
date: "04-06-2021",
value: 20.0,
},
{
date: "05-06-2021",
value: 23.99,
},
{
date: "06-06-2021",
value: 42.99,
},
{
date: "07-06-2021",
value: 47.29,
},
]
}
]
Here is what ive come up with so far:
const valueByDate = useMemo(
() =>
holdings
.map((data: any) => data)
.reduce((r: any, a: any) => {
// Find objects where ticker matches.
r[a.date] = r[a.date] || [];
// Push found object into array.
r[a.date].push({ type: a.type, value: a.value });
return r;
}, Object.create(null)),
[holdings],
);
// valueByDate creates an object like so...
let arr = {
'22-05-2021': [{ type: 'SELL', value: '9' }],
'22-06-2021': [{ type: 'SELL', value: '9' }],
'22-07-2021': [{ type: 'SELL', value: '9' }],
};
// Sum or Deduct VALUE per date depending on TYPE
const reduce = Object.values(valueByDate).forEach((element: any) =>
Object.values(element)
.flat()
.reduce((accumulator: any, currentValue: any) => {
if (currentValue.type == 'BUY') {
return (
parseFloat(accumulator) + parseFloat(currentValue.value)
);
} else if (currentValue.type == 'SELL') {
return (
parseFloat(accumulator) - parseFloat(currentValue.value)
);
}
}),
);
But I just have not been able to wrap my head around getting into the nested arrays and conditionally computing those values. Any insight would be a help.
Thank you