3
%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?

Dale
  • 1,289
  • 3
  • 16
  • 36

2 Answers2

7

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
]
machaval
  • 4,969
  • 14
  • 20
0

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
]