filter Vs takeWhile
Both of these functions can be used for selecting elements from the array for a given condition, The difference is "filter" returns all the element which matches condition but 'takeWhile' returns all the elements till the first failure.
JSON
input :
[
{
"id": "100",
"name": "Dataweave by"
},
{
"id": "100",
"name": "Arpan"
},
{
"id": "200",
"name": "Kumar"
},
{
"id": "100",
"name": "Sharma"
}
]
=========dwl=============
%dw 2.0
import * from dw::core::Arrays
output application/json
---
{
// use 'takeWhile' when you wants to select the element till first failure of given condition.
"takeWhile" : payload takeWhile ((item) -> item.id == "100" ) ,
//use 'filter' when you wants to select all the element for given condition.
"filter": payload filter ((item, index) -> item.id == "100")
}
=========output=============
{
"takeWhile": [
{
"id": "100",
"name": "Dataweave by"
},
{
"id": "100",
"name": "Arpan"
}
],
"filter": [
{
"id": "100",
"name": "Dataweave by"
},
{
"id": "100",
"name": "Arpan"
},
{
"id": "100",
"name": "Sharma"
}
]
}