Dataweave 2.2 What's the difference between takeWhile and filter?

Viewed 199
%dw 2.0
import * from dw::core::Arrays
output application/json
var arr = [0,1,2,4,3]
---
arr filter $ <= 2

and

%dw 2.0
import * from dw::core::Arrays
output application/json
var arr = [0,1,2,4,3]
---
arr takeWhile $ <= 2

They both give the same results. Is there any difference?

2 Answers

Hi Dale there is a difference takeWhile will stop taking elements with the first element that the condition is not satisfied that is not the case of filter so for this example [0,2,4,3,1]

With TakeWhile

%dw 2.0
import * from dw::core::Arrays
output application/json
var arr = [0,2,4,3,1]
---
arr takeWhile $ <= 2

Returns:

[
  0,
  2
]

With Filter

%dw 2.0
import * from dw::core::Arrays
output application/json
var arr = [0,2,4,3,1]
---
arr filter $ <= 2

Returns:

[
  0,
  2,
  1
]

takeWhile : Selects elements from the array while the condition is met but stops the selection process when it reaches an element that fails to satisfy the condition.

Script

%dw 2.0
import * from dw::core::Arrays
output application/json
var arr = [0,2,4,3,1]
---
arr takeWhile $ <= 2

Output

[
  0,
  2
]

filter : To select all elements that meet the condition, use the function. Script

%dw 2.0
import * from dw::core::Arrays
output application/json
var arr = [0,2,4,3,1]
---
arr filter $ <= 2

Output

[
  0,
  2,
  1
]
Related