cancel
Showing results forย 
Search instead forย 
Did you mean:ย 

Sum of values in array of objects without reduce function

Tanmay_Sarkar
New Contributor III

Hello all,

I stumbled upon a situation where I have to find out a sum of a certain key in the objects residing in an array without reducing the objects? What I mean to say is, here is the input:

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

The output that I am expecting should look like:

[
{
key1: value1,
key2: 10,
sum: 60
},
{
key1: value2,
key2: 20,
sum: 60
},
{
key1: value3,
key2: 30,
sum: 60
}
]

The total sum of key 2 values should be pushed into each object as a new key.

Can some one please suggest how to deal with this? Reducing wonโ€™t be the optimal solution as it would discard the objects and just add a new object with the total sum.

Thanks.

1 ACCEPTED SOLUTION

skatpally
Former Employee

You can use merge function too.

https://docs-snaplogic.atlassian.net/wiki/spaces/SD/pages/1439367/Object+Functions+and+Properties#Ob...

Community_Example_2021_05_11.slp (3.5 KB)

$group.map(x=>x.merge({โ€œsumโ€:$group.map(item => item.key2).reduce((accum, currentValue) => accum + currentValue)}))

View solution in original post

7 REPLIES 7

Tanmay_Sarkar
New Contributor III

This expression helped for now:
jsonPath($, โ€œgroup[*]โ€).map(item => item.key2).reduce((prev, next) => prev + next)

Mapped this to field โ€œsumโ€ and pushed it into the array.

Is there any other way as well to achieve this?

koryknick
Employee
Employee

@Tanmay_Sarkar - I havenโ€™t put an example together, but you should be able to do this with a combination of map() and reduce() functions. Looking at the full spec of the Array.map() function, you can access the array as one of the parameters:

@koryknick Thanks a lot, eventually map and merge function helped.

skatpally
Former Employee

You can use merge function too.

https://docs-snaplogic.atlassian.net/wiki/spaces/SD/pages/1439367/Object+Functions+and+Properties#Ob...

Community_Example_2021_05_11.slp (3.5 KB)

$group.map(x=>x.merge({โ€œsumโ€:$group.map(item => item.key2).reduce((accum, currentValue) => accum + currentValue)}))