Jessy - 1 year ago 121
Java Question

# How to flatten 2D array to 1D array?

How can I flatten the 2 dimensions array

`int originalArray[][]`
to 1 dimension array?

``````    int a [] = {1,2,6,7,2};
int b [] = {2,44,55,2};
int c [] = {2,44,511,33};

int originalArray [][] = new int[][]{a,b,c};
``````

A simple for loop will do, it is not difficult, but will depend on the order you wat to copy the values. For instance (based on the fact that in your example the arrays all have the same length):

``````int[] newArray = new int[3 * a.length];
int index = 0;
for (int n = 0; n < a.length; n++) {
newArray[index++] = a[n];
newArray[index++] = b[n];
newArray[index++] = c[n];
}
``````

or (different order, a, b, c can be of different lengths):

``````int[] newArray = new int[a.length + b.length + c.length];
System.arrayCopy(a, 0, newArray, 0, a.length);
System.arrayCopy(b, 0, newArray, a.length, b.length);
System.arrayCopy(c, 0, newArray, a.length + b.length, c.length);
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download