Contact Us 1-800-596-4880

Pick Top Elements

DataWeave 2.2 is compatible and bundled with Mule 4.2. This version of Mule reached its End of Life on May 2, 2023, when Extended Support ended.

Deployments of new applications to CloudHub that use this version of Mule are no longer allowed. Only in-place updates to applications are permitted.

MuleSoft recommends that you upgrade to the latest version of Mule 4 that is in Standard Support so that your applications run with the latest fixes and security enhancements.

This DataWeave 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. Before you begin, note that DataWeave version 2 (%dw 2.0) is for Mule 4 apps. For a Mule 3 app, refer to DataWeave 1.0 (%dw 1.0) examples, within the Mule 3.9 documentation set. For other Mule versions, you can use the Mule Runtime version selector in the table of contents.

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
%dw 2.0
output application/json
---
{
    TopCandidateList: (payload.candidates map ((candidate) -> {
        firstName: candidate.name,
        rank: candidate.score
    }) orderBy $.rank) [ -payload.availablePositions to -1]
}
Input
{
 "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
{
  "TopCandidateList": [
    {
      "firstName": "Simon Wilson",
      "rank": 84
    },
    {
      "firstName": "Amalia Silva",
      "rank": 96
    },
    {
      "firstName": "Gunther Govan",
      "rank": 99
    }
  ]
}