Trying to make calculations with array inside object

Hi there! I'm not a very experienced programmer, but I'm amazed with retool and learning a lot through it and this community. Trying to build a trading journal.

I can make a get RESTQuery request and retrieve data an plot it as chart. I made a dataset from the profit (or loss) generated on each trade.

Now I wanted to calculate my balance after each trade. Let's say my initial balance is $1000.

The data source is now an array with 9 values, I need to have a formula that adds $1000 to the first value of the array, then add the second value to the first, then add the third value to the second and so on. Something like:

New array:
1: 1000 + formatDataAsObject(['profit'] (array first value) = x
2: x + formatDataAsObject(['profit'] (array second value) = x1
3: x1 + formatDataAsObject(['profit'] (array third value) = x2

Can anyone help with that? Thank you!

Hey @loolmp! The JavaScript .reduce function that's on all arrays is made largely for situations like this! It might be worth checking out. You can do something like:

formatDataAsObject(['profit'].reduce((total, tradeProfit) => total + tradeProfit, 1000);

or (slightly smaller), trade) => total + trade.profit, 1000);

Do either of those work for you?

When you use reduce you pass it a function that takes in the current accumulation (total) and the next item in your array to iterate over (tradeProfit or trade). Then whatever that function returns gets passed on as the accumulation. The 1000 in the end is the custom starting value, otherwise it'll just default to the first item in the array.