cancel
Showing results forย
Did you mean:ย

## Cumulative sum of a value in an array

New Contributor III

Hi Everyone,

I need help on an expression solution. The โsumโ should be the sum of the value(s) of โkey2โ from previous records till the current record within the array.

Iโm trying to make it using the โreduceโ function.

Input:

``````[
{
"key1": "value1",
"key2": 10
},
{
"key1": "value2",
"key2": 20
},
{
"key1": "value3",
"key2": 30
}
]
``````

Expected Output:

``````[
{
"key1": "value1",
"key2": 10,
"sum": 10
},
{
"key1": "value2",
"key2": 20,
"sum": 30
},
{
"key1": "value3",
"key2": 30,
"sum": 60
}
]
``````
1 ACCEPTED SOLUTION
Valued Contributor

Hereโs a corrected version of the expression:

`\$array.map((x,index)=> index==0 ? x.extend({sum:x.key2}) : x.extend({sum:\$array.slice(0,index+1).reduce((acc,curr)=> acc+curr.key2,0)}))`

Let me know if this works for you, and I will explain in details on how the expression works.

6 REPLIES 6
Valued Contributor

Hey @spinaka,

If the records are in an array, than use the following expression:

`\$array.reduce((acc,curr)=> acc+curr.key2, 0)`

Or if you are able, you can split the array and use the Aggregate snap with SUM function selected.

Regards,
Bojan

Blockquote

New Contributor III

Hi @bojanvelevski, Thanks for the response.
This Aggregation just gives the sum of all the values that is 60., but we need the cumulative sum in every record as shown in the example output.

sum = sum in the previous record + key2 in the current record.

Valued Contributor

Hereโs a corrected version of the expression:

`\$array.map((x,index)=> index==0 ? x.extend({sum:x.key2}) : x.extend({sum:\$array.slice(0,index+1).reduce((acc,curr)=> acc+curr.key2,0)}))`

Let me know if this works for you, and I will explain in details on how the expression works.

New Contributor III

This is perfect @bojanvelevski
I was trying with index, map and your expression is better than mine. ๐

Would you mind explaining the reduce function used here?