Nav

Example: Pick Top Elements

This example sorts an array of candidates by the score they got in a test, then picks only the ones with the best score, as many as there are open positions to fill.

This example uses the following:

  • map to go through each of the candidates in the input.

  • orderBy to order the list of candidates according to their score.

  • [n to n] to select only a section of the full array of candidates. As the array in ordered in ascending order, the top candidates are at the end of the array, so you must use negative indexes. With the provided input, it selects from -3 to -1, -1 being the last index in the array.

DataWeave

         
      
1
2
3
4
5
6
7
8
9
%dw 2.0
output application/json
---
{
    TopCandidateList: (payload.candidates map ((candidate) -> {
        firstName: candidate.name,
        rank: candidate.score
    }) orderBy $.rank) [ -payload.availablePositions to -1]
}
Input

         
      
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
{
 "availablePositions": 3,
 "candidates":
    [
      {
        "name":"Gunther Govan",
        "score":99
      },
       {
        "name":"Michael Patrick",
        "score":35
      },
      {
        "name":"Amalia Silva",
        "score":96
      },
       {
        "name":"Tom Mathews",
        "score":40
      },
      {
        "name":"Simon Wilson",
        "score":84
      },
      {
        "name":"Janet Nguyen",
        "score":52
      }
    ]
}
Output

         
      
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
  "TopCandidateList": [
    {
      "firstName": "Simon Wilson",
      "rank": 84
    },
    {
      "firstName": "Amalia Silva",
      "rank": 96
    },
    {
      "firstName": "Gunther Govan",
      "rank": 99
    }
  ]
}

In this topic: