Reputation: 17
I need to compare the field(Doc) in a single array and if their values matched I need to calculate the minimum value of another filed(Number)
Here is an example of the array:
[
{
"Doc": "test1",
"Number": 91
},
{
"Doc": "test1",
"Number": 94
},
{
"Doc": "test1",
"Number": 40
},
{
"Doc": "test2",
"Number": 82
},
{
"Doc": "test2",
"Number": 80
}
]
In the above array, if Doc is same I want to get the minimum value of the Number field. My output should be like this:
[
{
"Doc": "test1",
"Number": 40
}
{
"Doc": "test2",
"Number": 80
}
]
Upvotes: 1
Views: 856
Reputation: 17
Both of these answers worked for me.
Solution# 1:
%dw 2.0
output application/json
---
payload groupBy ((item, index) -> item.Doc)
mapObject ((value, key, index) -> (key): min(value.Number) )
pluck ((value, key, index) -> { Doc: key, Number: value})
Solution# 2:
%dw 2.0
output application/json
fun byDoc() = valuesOf(payload groupBy ((item, index) -> item.Doc))
fun minNumber(array : Array) = array minBy ((item) -> item.Number)
---
byDoc() map ((item, index) -> minNumber(item))
Upvotes: 0
Reputation: 467
payload groupBy $.Doc mapObject ((item, key, index) -> (key): min(item.Number) ) pluck ((item, key, index) -> { Doc: key, Number: item})
Upvotes: 0
Reputation: 25812
First group by Doc, mapObject() to get the minimum of each group, then pluck() to get the expected output.
%dw 2.0
output application/json
---
payload groupBy ((item, index) -> item.Doc)
mapObject ((value, key, index) -> (key): min(value.Number) )
pluck ((value, key, index) -> { Doc: key, Number: value})
Input:
[
{
"Doc": "STR23756",
"Number": 91
},
{
"Doc": "STR23756",
"Number": 94
},
{
"Doc": "STR23756",
"Number": 40
},
{
"Doc": "STR23757",
"Number": 82
},
{
"Doc": "STR23757",
"Number": 80
}
]
Output:
[
{
"Doc": "STR23756",
"Number": 40
},
{
"Doc": "STR23757",
"Number": 80
}
]
Upvotes: 1
Reputation: 2835
An alternative using valuesOf
:
%dw 2.0
output application/json
fun byDoc() = valuesOf(payload groupBy ((item, index) -> item.Doc))
fun minNumber(array : Array) = array minBy ((item) -> item.Number)
---
byDoc() map ((item, index) -> minNumber(item))
Upvotes: 2