# Split one-dimensional array into two-dimensional array JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

We are required to write a function that takes in a one-dimensional array as the first argument and a number n as the second argument and we have to make n subarrays inside of the parent array (**if possible) and divide elements into them accordingly.

** if the array contains 9 elements and we asked to make 4 subarrays, then dividing 2 elements in each subarray creates 5 subarrays and 3 in each creates 3, so in such cases we have to fallback to nearest lowest level (3 in this case) because our requirement is to distribute equal number of elements in each subarray except the last one in some special cases.

For example −

// if the input array is:
const arr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'];
// and the number is 2
//then the output should be:
const output = [ [ 'A', 'B', 'C', 'D', 'E' ], [ 'F', 'G', 'H', 'I' ] ];

Let’s write the code for this function −

## Example

const arr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'];
const splitArray = (arr, rows) => {
const itemsPerRow = Math.ceil(arr.length / rows);
return arr.reduce((acc, val, ind) => {
const currentRow = Math.floor(ind / itemsPerRow);
if(!acc[currentRow]){
acc[currentRow] = [val];
}else{
acc[currentRow].push(val);
};
return acc;
}, []);
};
console.log(splitArray(arr, 2));

## Output

The output in the console will be −

[ [ 'A', 'B', 'C', 'D', 'E' ], [ 'F', 'G', 'H', 'I' ] ]
Published on 26-Aug-2020 09:49:42