FQL v4 will be decommissioned on June 30, 2025. Ensure that you complete your migration from FQL v4 to FQL v10 by that date. For more details, review the migration guide. Contact support@fauna.com with any questions. |
Zip together two arrays
Problem
You want to "zip" two arrays together. ["A", "B", "O"]
and ["Apple",
"Banana", "Orange"]
should become [["A", "Apple"], ["B", "Banana"],
["O", "Orange"]]
.
Solution
Fauna doesn’t provide a Zip
function, but we can create one:
The following query calls the UDF with two arrays:
[ [ 'A', 'Apple' ], [ 'B', 'Banana' ], [ 'O', 'Orange' ] ]
[['A', 'Apple'], ['B', 'Banana'], ['C', 'Orange']]
[[A Apple] [B Banana] [O Orange]]
Arr(Arr(StringV(A), StringV(Apple)), Arr(StringV(B), StringV(Banana)), Arr(StringV(O), StringV(Orange)))
[ [ 'A', 'Apple' ], [ 'B', 'Banana' ], [ 'O', 'Orange' ] ]
The UDF handles the situation where either array is longer than the other:
[
[ [ 'A', 'Apple' ], [ 'B', 'Banana' ], [ null, 'Orange' ] ],
[ [ 'A', 'Apple' ], [ 'B', 'Banana' ], [ 'O', null ] ]
]
[[['A', 'Apple'], ['B', 'Banana'], [None, 'Orange']], [['A', 'Apple'], ['B', 'Banana'], ['O', None]]]
[[[A Apple] [B Banana] [{} Orange]] [[A Apple] [B Banana] [O {}]]]
Arr(Arr(Arr(StringV(A), StringV(Apple)), Arr(StringV(B), StringV(Banana)), Arr(NullV, StringV(Orange))), Arr(Arr(StringV(A), StringV(Apple)), Arr(StringV(B), StringV(Banana)), Arr(StringV(O), NullV)))
[
[ [ 'A', 'Apple' ], [ 'B', 'Banana' ], [ null, 'Orange' ] ],
[ [ 'A', 'Apple' ], [ 'B', 'Banana' ], [ 'O', null ] ]
]
Discussion
The main logic is within the Reduce
function call:
-
An empty array is provided as the initial accumulator.
-
The longest array is used as the list to iterate.
-
On each invocation, the reducer’s
Lambda
uses the size of the accumulator as the index into the two provided arrays, andSelect
is use to access the value and returnnull
if no value exists at that index.
Is this article helpful?
Tell Fauna how the article can be improved:
Visit Fauna's forums
or email docs@fauna.com
Thank you for your feedback!