'How to compare two or more fields in a single array and calculate minimum value

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
    }
]


Solution 1:[1]

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))

Solution 2:[2]

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
  }
]

Solution 3:[3]

%dw 2.0 output application/json

payload groupBy $.Doc mapObject ((item, key, index) -> (key): min(item.Number) ) pluck ((item, key, index) -> { Doc: key, Number: item})

Solution 4:[4]

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))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 afelisatti
Solution 2
Solution 3 Harsha Shivamurthy
Solution 4 Zak01