'Splitting array of objects in to multiple arrays by certain criteria
import * from dw::core::Arrays
var divideNr = 3
var payload = [1,2,3,4,5,1,2,3,4,1,2,3,4,5,6,1,2,3]
fun splitting (array1) =
if ((array1 splitAt divideNr).l[divideNr-1] == 2)
array1 splitAt divideNr
else
array1 splitAt divideNr-1
output application/json
---
splitting(payload)
So I am trying to divide the the array in to multiple arrays of max size three. The idea is that I cant have 1 and 2 in two seperate arrays. With splitAt I cut it in to two parts (left and right). Left is correct, but right one is array of remaining objects. I cant figure out how to continue iterating over remaining ones so in the end I get an array of arrays (with max amount if 3 objects and 1 followed by 2 not split in to two seperate arrays). In my real example there are way more different objects so I cant cut them at the same place every time.
Solution 1:[1]
Use divideBy() instead of splitAt():
import * from dw::core::Arrays
var divideNr = 3
var payload = [1,2,3,1,2,3,1,2,3,1,2,3]
output application/json
---
payload divideBy divideNr
Output:
[[1,2,3],[1,2,3],[1,2,3],[1,2,3]]
Note that your approach is not needed because there is a built-in function that achieves that. Having said that, to make it work you should modify your function to be a recursive function, applied to the remaining items.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | aled |
