Zak01
Zak01

Reputation: 17

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

Upvotes: 1

Views: 856

Answers (4)

Zak01
Zak01

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

Harsha Shivamurthy
Harsha Shivamurthy

Reputation: 467

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

Upvotes: 0

aled
aled

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

afelisatti
afelisatti

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

Related Questions