Write an Appian expression to convert a one-dimensional array into a two-dimensional array, where each sub-array contains exactly N elements.
Example:
Input: array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, N = 2
Output:
{ {1,2}, {3,4}, {5,6}, {7,8}, {9,10} }
Write an Appian expression to convert a one-dimensional array into a two-dimensional array, where each sub-array contains exactly N elements.
Example:
Input: array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, N = 2
Output:
{ {1,2}, {3,4}, {5,6}, {7,8}, {9,10} }
Answer
To split {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} into groups of N, first work out how many groups you need: ceiling(length(array) / N). Ten items with N = 2 gives 5 groups, and rounding up keeps a short last group when the length doesn’t divide evenly.
Then loop once per group with a!forEach(). Group G starts at position (G - 1) * N + 1 and takes the next N positions, which enumerate(N) generates as offsets. For group 3 with N = 2, that gives positions 5 and 6.
Pass those positions to index() to pull the values from the original array. Set its default to null() so positions past the end return null instead of an error. The result is {{1, 2}, {3, 4}, {5, 6}, {7, 8}, {9, 10}}.
Code:
Output:
Explanation:
Step 1: Define the input array
local!N is the number of elements in each group.
Step 2: Calculate the number of groups
length(local!array)is 10.10 / 2is 5.ceiling(5)is 5.
So local!list is 5, which means five groups are needed.
Step 3: Generate group numbers
enumerate(5) returns {0, 1, 2, 3, 4}. Adding 1 gives {1, 2, 3, 4, 5}, one number for each group that a!forEach() processes.
Step 4: Calculate the indexes for each group
With local!N = 2, enumerate(2) returns {0, 1}. For each group, the formula produces two array positions.
Step 5: See how the index formula works
The formula is:
G is the current group number (fv!item), and N is 2.
Group | Array indexes | Values returned |
|---|---|---|
1 | 1, 2 | 1, 2 |
2 | 3, 4 | 3, 4 |
3 | 5, 6 | 5, 6 |
4 | 7, 8 | 7, 8 |
5 | 9, 10 | 9, 10 |
For example, when fv!item = 3:
index() then retrieves elements 5 and 6 from the original array.
Step 6: What index() does here
It retrieves the elements at positions 5 and 6 and returns {5, 6}. The third argument, null(), is the default value returned if a requested index doesn’t exist.
Step 7: Final output
The expression returns a list of groups:
For more coding challenges visit : https://appianverse.com/coding
Try it yourself
Change the inputs or the expression and run it to see what it returns.
Independent evaluator: it approximates the Appian expression language and may differ from a real Appian environment. Verify anything that matters. Terms