Forum Discussion
Combine two arrays, alternating their elements
I'm thinking how one would go about doing this in PQ.
Input : arr1[] = {1, 2, 3, 4, 5, 6}
arr2[] = {11, 22, 33, 44}
Output: {1, 11, 2, 22, 3, 33, 4, 44, 5, 6}
Input : arr1[] = {1, 2, 3, 4, 5, 6, 7, 8}
arr2[] = {11, 22, 33, 44}
Output: {1, 11, 2, 22, 3, 33, 4, 44, 5, 6, 7, 8}I was thinking about using indexes with a different starting point
Table1: starting at 1 with a 2 increment step.
Table2: starting at 2 with a 2 increment step.
Append tables, order by index column and it should be ordered correctly.
Perhaps you have a more efficient suggestion?
KR,
João
Assuming the arrays are list objects in the Query editor, you can use this function:
List.Select(List.Combine(List.Zip({Array1, Array2})), each _ <> null)
4 Replies
- ImkeFCommunity Champion
Assuming the arrays are list objects in the Query editor, you can use this function:
List.Select(List.Combine(List.Zip({Array1, Array2})), each _ <> null)- rohanjaiswalFrequent Visitor
Output: {1, 11, 2, 22, 3, 33, 4, 44, 5, 6}ImkeF How to get each combination into separate row ?
ID value 1 1,11 2 2,22 3 3,33 - AnonymousNot applicable
you could use the tool Merge Columns, after having selected the involved columns:
then choice the separator you like:
PS
I intruded into the discussion to show a different approach, but only for fun.
I just wanted to experiment with recursion and I wrote this Anonymous.let interleave=(a1,a2,pos) => let la1=List.Count(a1), la2=List.Count(a2), gl=if la1 >= la2 then a1 else a2, ll=if la1 < la2 then a1 else a2, ins_a1=List.InsertRange(gl,2*pos+1,{ll{pos}}), p=pos+1 in if p < List.Min({la1,la2}) then @interleave(ins_a1,ll,p) else ins_a1 in interleave