# Transpose a 2D Array type Internal Table

Hello Everyone,

This is my first blog post in SAP community and I hope this post gives a trivial yet powerful capability of ABAP as a programming language.

From developer perspective ABAP gives most of the in built features like Sorting, Binary Search etc.,

In this blog post I tried to implement most commonly used open source concepts like transposing 2 dimensional array using an internal table using ABAP. I have used ABAP 7.50 syntaxes (a must try from your side as well!) in the logic to shrink the lines of code.

Without wasting time let’s get into the topics.

Transposing a 2D array using Internal table:

Transposing simply means “cause (two or more things) to exchange places”. In our example Row values become columns and vice versa.

In open source world a 2D Array looks like below,

[[1, 1, 1],
[2, 2, 2],
[3, 3, 3]]

and the transposed form looks like below,

[[1, 2, 3],
[1, 2, 3],
[1, 2, 3]]

Same thing cannot be represented in ABAP because we have only internal tables as data structures. In ABAP world the same above Array becomes an internal table with 3 columns and 3 rows.

lt_2d_array VALUE #f1 f2 f3 )
f1 f2 f3 )
f1 f2 f3 ) ).

Looking similar to above Array? Now let’s try to write a small piece of code to get the “Transpose” effect. We need to exchange the values from each column of each row to particular column of individual rows.

For example f1 value of row 1 doesn’t need to be exchanged, but f2 value of row 1 should be exchanged with f1 value of row 2. That is the base for our logic.

As we have fixed number of columns I have hard coded the number columns.

``````TYPES: BEGIN OF ty_2d_array, f1 TYPE i, f2 TYPE i, f3 TYPE i, END OF ty_2d_array.
DATA: lt_2d_array TYPE STANDARD TABLE OF ty_2d_array WITH DEFAULT KEY. * Prepopulate the values.
lt_2d_array = VALUE #( ( f1 = 1 f2 = 1 f3 = 1 ) ( f1 = 2 f2 = 2 f3 = 2 ) ( f1 = 3 f2 = 3 f3 = 3 ) ).
DATA(lt_2d_array_before) = lt_2d_array. LOOP AT lt_2d_array ASSIGNING FIELD-SYMBOL(<fs_2d_array_in>). DATA(lv_tabix) = sy-tabix. DO 3 TIMES. " Hard coded column count IF lv_tabix < sy-index. ASSIGN COMPONENT sy-index OF STRUCTURE <fs_2d_array_in> TO FIELD-SYMBOL(<fv_swap_src>). " Swap the column of this index with next record. READ TABLE lt_2d_array ASSIGNING FIELD-SYMBOL(<fs_next_row>) INDEX sy-index. IF sy-subrc = 0. ASSIGN COMPONENT lv_tabix OF STRUCTURE <fs_next_row> TO FIELD-SYMBOL(<fv_swap_tar>). DATA(tmp) = CONV i( <fv_swap_src> ). <fv_swap_src> = <fv_swap_tar>. <fv_swap_tar> = tmp. ENDIF. ENDIF. ENDDO.
ENDLOOP. * Print to the demo output.
cl_demo_output=>write( data = lt_2d_array_before name = |Before Transpose| ).
cl_demo_output=>display( data = lt_2d_array name = |After Transpose| ).``````

Now let’s see the output,

See how our ABAP output is looking similar to normal JS Array! Looks nice? Yesss!

Hope you enjoyed this post! Thank you everyone for taking time to read the content!

Enjoy Coding,

Akhilesh