Search

Dark theme | Light theme

February 23, 2022

DataWeave Delight: Reversing the items in an array

To reverse the order of the items in the array we have two possible solutions in DataWeave. The first solution uses the index operator to access items in an array ([...]). We can define a range as value for the index operator to get all elements that have a index value that is part of the range. For example we could use [1 to 3] to get the second up to the fourth items from the array. The value -1 can be used to indicate the last index in the array, so we could get a new array where the items are in reversed order by using the range [-1 to 0].

The second option is to use the orderBy function for an array from the dw::Core module. The function takes as first argument an array and the second argument is a criteria function that is applied for each element. The criteria function will get the array element value and index. The output of the function is used for the ordering of the resulting array. To reverse the order we can negate the index value of the criteria function and we get a new array in reverse order: ((item, index) -> -index).

In the following example we use both ways to reverse the order of an array:

Source

%dw 2.0

var list = [2, 1, 4, 5, 3]

output application/json
---
{
    // Using index operator.
    reverseIndices: list[-1 to 0],

    // Using orderBy with criteria function.
    reverseOrderBy: list orderBy ((item, index) -> -index),

    // Using orderBy with shorthand notation for criteria function.
    reverseOrderByShorthand: list orderBy -$$
}

Output

{
  "reverseOrderBy": [
    3,
    5,
    4,
    1,
    2
  ],
  "reverseIndices": [
    3,
    5,
    4,
    1,
    2
  ],
  "reverseOrderByShorthand": [
    3,
    5,
    4,
    1,
    2
  ]
}

Written with DataWeave 2.4.