---
schema_version: "1"
id: 5ef6c9b679d3b05f4f1e338ee84ed02b461d6858d1cccbbd53d98abfdec626ba
title: Pick Top Elements
collection: mulesoft
version: current
locale: en-us
portal_url: https://docs.salesforce.com/mulesoft/current/en-us/dataweave/2.6/dataweave-cookbook-pick-top-elements.md
canonical_url: https://docs.mulesoft.com/dataweave/2.6/dataweave-cookbook-pick-top-elements
source_site: docs.mulesoft.com
content_type: documentation
content_hash: 76a25383e7bfca989fc856acb29a2dbe6f587fb20f23f032afc96dc72a3de12e
description: MuleSoft Documentation Site
release: "2.6"
latest: false
---
---
product: DataWeave
version: 2.6
keywords: studio, anypoint, transform, transformer, format, xml, json, metadata, dataweave, data weave, datamapper, dwl, dfl, dw, output structure, input structure, map, mapping
---

# Pick Top Elements

> For the full documentation index, see: https://docs.mulesoft.com/llms.txt

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.

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 Script:

```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 JSON Payload:

```json
{
  "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 JSON:

```json
{
  "TopCandidateList": [
    {
      "firstName": "Simon Wilson",
      "rank": 84
    },
    {
      "firstName": "Amalia Silva",
      "rank": 96
    },
    {
      "firstName": "Gunther Govan",
      "rank": 99
    }
  ]
}
```

## Related Examples

- [Output Self-closing XML tags](https://docs.mulesoft.com/dataweave/2.6/dataweave-cookbook-output-self-closing-xml-tags)

- [Remove Specified XML Attributes](https://docs.mulesoft.com/dataweave/2.6/dataweave-cookbook-remove-certain-xml-attributes)

## See Also

- [DataWeave Selectors](https://docs.mulesoft.com/dataweave/2.6/dataweave-selectors)

- [DataWeave Cookbook](https://docs.mulesoft.com/dataweave/2.6/dataweave-cookbook)
