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

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

3 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

2 years ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

2 years ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

2 years ago