Few ways to skip the first element of an array using DataWeave 2.0
So most recently I have an scenario where some of the data I got from an external system I needed to skip the first element of an array since was a constant value I won’t need.
So after get my question over the Mulesoft community few ways to do this came up.
Right after asking the question and Google it for a bit I saw the option to use the function slice but fortunatelly was not the only way
Slice
“Selects the interval of elements that satisfy the condition: from <= indexOf(array) < until
”
%dw 2.0
import * from dw::core::Arrays
output application/json
var arr = [0,1,2,3,4,5]
---
slice(arr, 1, 4)
In case you need to specify the size of the array it will be something like:
%dw 2.0
import * from dw::core::Arrays
output application/json
var arr = [0,1,2,3,4,5]
---
slice(arr, 1, sizeOf(arr))
Drop
“Drops the first n
elements. It returns the original array when n <= 0
and an empty array when n > sizeOf(array)
.”
%dw 2.0
import * from dw::core::Arrays
var numbers= [0,1,2,3,4]
output application/json
---
drop(numbers, 1)
Range selection
Finally setting a range selection makes it easy and clear and we achieve the result not even importing the core Arrays.
%dw 2.0
output application/json
var a = [0,1,2,3,4]
---
a [1 to -1]
I feel so glad the community got involved right away and suggested multiple solutions and now I hope I can share it it all of you.