Range selector (anIndex to anotherIndex)

Range selector (anIndex to anotherIndex)

If you need multiple sequential values from an Array, DataWeave allows you to select a range of values with the range selector ([n to m]). Instead of returning a single value like the index selector does, it will return an Array of values:


Input:

[“prod”, “qa”, “dev”]

DW Script:

%dw 2.0

output json

payload[0 to 1]

Output:

[“prod”, “qa”]


Just like with the index selector, negative indexes can be used to select a range of values starting from the end of the Array.

The to selector returns values of matching indices in an array or string. You can also use it to reverse the order of the indices in the range. The selector treats characters in the string as indices.

  • Selecting an index from an array:

    • [1,2,3,4][0] returns 1


      The index of the first element in an array is always 0.

    • [1,2,3,4][3] returns 4

Range Selector Over an Array

Range selectors limit the output to only the elements specified by the range on that specific order. This selector allows you to slice an array or even invert it.

DataWeave Script:

%dw 2.0

output application/json

{

slice: [0,1,2][0 to 1],

last: [0,1,2][-1 to 0]

}

Output JSON:

{

“slice”: [

0,

1

],

“last”: [

2,

1,

0

]

}

Range Selector Over a String

The Range selector limits the output to only the elements specified by the range on that specific order, treating the string as an array of characters. This selector enables you to slice a string or invert it.

DataWeave Script:

%dw 2.0

output application/json

{

slice: “DataWeave”[0 to 1],

middle : “superfragilisticexpialadocious”[10 to 13],

last: “DataWeave”[-1 to 0]

}

Output JSON:

{

“slice”: “Da”,

“middle”: “list”,

“last”: “evaeWataD”

}

Follow Me

If you like my post please follow me to read my latest post on programming and technology.

Instagram

Facebook

Recent Posts

Minimum Cost to Paint Houses with K Colors

A builder plans to construct N houses in a row, where each house can be…

1 day ago

Longest Absolute Path in File System Representation

Find the length of the longest absolute path to a file within the abstracted file…

3 weeks ago

Efficient Order Log Storage

You manage an e-commerce website and need to keep track of the last N order…

1 month ago

Select a Random Element from a Stream

You are given a stream of elements that is too large to fit into memory.…

1 month ago

Estimate π Using Monte Carlo Method

The formula for the area of a circle is given by πr². Use the Monte…

2 months ago

Longest Substring with K Distinct Characters

Given an integer k and a string s, write a function to determine the length…

2 months ago