spinaka
4 years agoNew Contributor III
Cumulative sum of a value in an array
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
}
]
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.